Using Javascript To Load Checkbox Values Into A String
What I want visitors to be able to do is: tick any number of checkboxes for products they'd like to enquire about, and have a link appear at the bottom of the page after they've ti
Solution 1:
It looks like the below produces the string.
$("button").on("click", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&" + vals
console.log(str)
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><inputtype="checkbox"id="selected"name="selected"value="Blue"class="products"> Blue<br><inputtype="checkbox"id="selected"name="selected"value="Green"class="products"> Green<br><inputtype="checkbox"id="selected"name="selected"value="Purple"class="products"> Purple
<br><button>button</button>
Solution 2:
Get your string of values like this
var checked = Array.prototype.slice.call(document.querySelectorAll('.products:checked')).map(function(el){
return el.value;
}).join(',');
Then create a <a>
element
var aEl = document.createElement("a");
aEl.setAttribute("href", "http://example.com/?subject=Products&checked=" + checked);
And place it where you want (for this exemple, at the end of the body)
document.body.appendChild = aEl;
Or in an empty and existent <div>
// HTML
<div id="myEmptyDiv"></div>
// JSdocument.getElementById('myEmptyDiv').innerHTML = aEl;
Here a Fiddle with all those things and a change
listener
Solution 3:
This should get what you need:
var checked = Array.prototype.slice.call(document.querySelectorAll('[name=selected]:checked'));
var values = checked.map(function(el) {
return el.value;
});
console.log(values.join(','));
es6 version:
let checked = Array.from(document.querySelectorAll('[name=selected]:checked'));
let values = checked.map(el => el.value);
console.log(values.join(','));
Post a Comment for "Using Javascript To Load Checkbox Values Into A String"