0

So I had been using this generic code to create a URL from the form elements

function submiturl() {
    url="Search.do?call=JS"; 
    var elem = document.getElementById('searchInput').elements;
    for(var i = 0; i < elem.length; i++) {
        url = url + "&" + escape(elem[i].name) + "=" + escape(elem[i].value);
    }
    url = url.substring(0,(url.length-1));
   alert(url);
}

however it does not handle checkboxes properly - I only want to add to the URL if the checkboxes are checked. So if you had this html

<html>
<body>
<form name="searchInput" id ="searchInput">
    <input name="first" type="checkbox" value="123"/>One two three
    <input name="second" type="checkbox" value="456"/>Four five six
    <button type="button" onClick="submiturl();">Submit</button>
</form>
</body>
</html>

it will create the URL using the value for both checkboxes regardless if they were checked or not.

So how can I modify my javascript to check if it is a checkbox and is checked?

thanks!

1
  • Have you tried using if (elem[i].checked) Commented May 21, 2012 at 14:54

3 Answers 3

1

Inside your for-loop do this:

if (elem[i].type != "checkbox" || elem[i].checked)
    url = url + ...
Sign up to request clarification or add additional context in comments.

Comments

0
function submiturl() {
    var url="Search.do?call=JS", 
        els = document.getElementById("searchInput").elements
    ;
    for(var el, i = 0, n = els.length; i < n; i++) {
        el = els[i];
        if (el.checked || el.type !== "checkbox") {
            url += "&" + encodeURIComponent(el.name) + 
                   "=" + encodeURIComponent(el.value)
            ;
        }
    }
    alert(url);
}

Comments

0

Is it a checkbox?

typeof elem[i].attributes['type'] != 'undefined' &&
elem[i].attributes['type'].value == 'checkbox'

Is it checked?

typeof elem[i].attributes['checked'] != 'undefined' &&
elem[i].attributes['checked'].value == 'checked'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.