I want to have a web button that is generated dynamically depending on which checkboxes a user selects, without needing to reload the page. I guess jQuery is the way to do this but I am a complete noob with jQuery/JavaScript (trying to learn on the fly, which isn't easy).
Ultimately, I think it s/b a 2-step process: (1) as the user checks checkboxes, store them in an array and del开发者_运维问答imit them, and (2) output html to create a button that dynamically uses the delimited array values.
HTML form:
<input type="checkbox" name="catChoices[]" value="80s" />80s<br />
<input type="checkbox" name="catChoices[]" value="90s" />90s<br />
<input type="checkbox" name="catChoices[]" value="00s" />00s<br />
Being a jQuery/JS novice, I've only come up with this to do step 1 mentioned above. I don't know if this is on the right track or completely off:
jQuery:
$(document).ready(function() {
$("input").click(function() {
var checkValues = $('input[name=catChoices]:checked').map(function() {
return $(this).val();
}).get();
str = checkValues.join(',');
});
});
I also don't know how to incorporate step 2 (get the button to be created dynamically with jQuery). The solutions I've googled show how to pass the values to html/PHP, which requires a page refresh, but I want the button to update on-the-fly as the user checks/unchecks checkboxes.
Thanks for your help!
Are you sure you want to use such a non-standard (for the web) format?
Have you thought about doing this:
var data = $('input[name="catChoices[]"]').serialize();
This is smart enough to only include checked checkboxes.
Granted, you can always convert it to a comma-separated list by doing
data = data.replace(/&/g, ',').replace(/catChoices%5B%5D=/g, '')
Creating a button is as simple as:
$('<button>', { val: data })
or
$('<input>', { type: 'submit', val: data })
a different api is preferred by some:
$('<input type="submit">').val(data)
Try this. Name of the input box is catChoices[] and it should be in quotes.
$("input").click(function() {
var checkValues = $('input[name="catChoices[]"]:checked').map(function() {
return $(this).val();
}).get();
str = checkValues.join(',');
alert(str );
});
精彩评论