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 ticked the first. They click the link and it autofills a form.

I've got the latter part sussed using a query, but I need to get comma separated checkbox values and feed them into a string for use in my link - ie if my checkbox code is:

<input type="checkbox" id="selected" name="selected" value="Blue" class="products"><br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"><br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products">

它看起来像下面产生的字符串。

$("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)	
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>

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>
// JS
document.getElementById('myEmptyDiv').innerHTML = aEl;

Here a Fiddle with all those things and a change listener


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(','));
链接地址: http://www.djcxy.com/p/56014.html

上一篇: 通过复选框更改div的内容

下一篇: 使用JavaScript将复选框的值加载到字符串中