AJAX multiple checkboxes / multiselect - javascript

Alrighty then, howdy first off; quick question I have a form that has multiple check boxes with the same name (i.e. -
<input type="checkbox" name="myname[]" value="1" />
<input type="checkbox" name="myname[]" value="1" />
<input type="checkbox" name="myname[]" value="2" />
<input type="checkbox" name="myname[]" value="3" />
<input type="checkbox" name="myname[]" value="4" />
)
I am not using JQuery as I don't need that much baggage it is a very simple script that does does what is says on the tin, just serialize a form for use in an ajax post request. I would like to know though how to serialize the multiple checkboxes above for correct use in php.

I think the easiest way would be to grab all the checkboxes with document.getElementsByName and loop to get what's checked.
var checkedValues = [];
var allCheckboxes = document.getElementsByName("myname[]");
for(var i = 0; i < allCheckboxes.length; i++){
if (allCheckboxes[i].checked)
checkedValues.push(allCheckboxes[i].value);
}
I assume PHP can treat a comma-delimited list of values as an array:
checkedValues.join(); //tested and produces ---> 0,3,4

Related

Validating if atleast one checkbox is checked or one input field is filled

I need better validation logic, where some Checkboxes and some input fields are grouped together.
The user either have to check at least one checkbox or have to fill at least one input box.
If a checkbox is checked or an input field is filled then the complete group is validated.
What will be the best possible way to validate such a situation?
e.g
<input class="checkbox" type="checkbox" name="check-deal" value="1" grouped="deal" >
<input class="checkbox" type="checkbox" name="check-deal" value="2" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="3" grouped="deal">
<input class="checkbox" type="checkbox" name="check-deal" value="4" grouped="deal">
<input class="input-group" type="text" name="deal-name1" value="" grouped="deal">
<input class="input-group" type="text" name="deal-name2" value="" grouped="deal">
I have defined an extra attribute grouped for all input and checkboxes that should be grouped togather
but getting no idea how to validate the group as best practice.
DEMO
Point No.1 : There isn't any attribute called grouped for html as of my knowledge but I would suggest you to use data-* prefixed attribute names like data-grouped or data-anyname which is valid
Point No.2 : I rather categorized your checkboxes and textboxes into separate divs and below is how it is:
<div class="chkbox">
<input class="checkbox" type="checkbox" name="check-deal" value="1" />
<input class="checkbox" type="checkbox" name="check-deal" value="2" />
<input class="checkbox" type="checkbox" name="check-deal" value="3" />
<input class="checkbox" type="checkbox" name="check-deal" value="4" />
</div>
<div class="txtbxs">
<input class="input-group" type="text" name="deal-name1" value="" />
<input class="input-group" type="text" name="deal-name2" value="" />
</div>
<button class="btnValidate">Validate</button>
Point No.3 : Below is how you can validate using jquery
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length; //get checkbox checked length
var filledText=$(".txtbxs .input-group").val()!="";
//get bool value whether any of the text box is filled or not
if(chkLength || filledText) //check with or condition
alert('valid')
else
alert('invalid');
});
UPDATE
DEMO
As #AkshatG pointed in his answer the discrepancy was there in my answer so I've edited it and here is the updated solution.
$('.btnValidate').on('click',function(){
var chkLength=$('.chkbox .checkbox:checked').length;
var filledText=false; //First set it to false
$.each($(".txtbxs .input-group"),function(index,value){
if($(value).val()!="")
{
filledText=true//if it finds any value then set it to true
return;//break from $.each
}
})
if(chkLength || filledText)
alert('valid')
else
alert('invalid');
});
You first need to take count of each validations. And then check if any of the two has count greater than 0 or not. Guruprasad's answer won't work if you enter text on second textbox because it won't filter all the textboxes. You have to use filter function for this :
$("input[type='text'],textarea").filter(function() {
return $(this).val() != "";
}).length;
Here's a jsfiddle :
http://jsfiddle.net/myfLgpdv/
Hope this helps.

Possible to pass several array items using 1 attribute?

I have a group of tick boxes with 1 select all box at the top
<input type="checkbox" id="1195" value="All" />
<input type="checkbox" name="GroupA" title="TickboxA" value="TickboxA" id="TickboxA" />
<input type="checkbox" name="GroupA" title="TickboxB" value="TickboxB" id="TickboxB" />
<input type="checkbox" name="GroupA" title="TickboxC" value="TickboxC" id="TickboxC" />
<input type="checkbox" name="GroupA" title="TickboxD" value="TickboxD" id="TickboxD" />
I'm passing all the checks to an array so I can pass it around the site like so:
$('input').on('ifClicked', function (event) {
addRemoveService(document.getElementById(this.title));
setItemArray();
document.getElementById('mydoc').value = "";
for (var i = 0; i < itemIdArray.length; i++) {
setInterestedIn(i);
}
});
I have some jquery that will tick all the boxes for me if i click on the top checkbox - Everything is working perfect, except if i tick on the 'all' checkbox - I can't pass all the titles of all the other boxes to the array - what I want to do is something like:
<input type="checkbox" id="1195" value="All" title="TickboxA,TickboxB,TickboxC,TickboxD" />
If that makes sense? Is there an easy way to do this?

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Advanced use of jQuery serializeArray()

I'm currently submitting a form via ajax and pass in a manually created data variable that looks a bit like this:
var data = 'answer1='
+ $("input[name=question_1]:checked").val()
+ '&q1_option=' + $("input[name=question_1]:checked").attr("id")
This continues throughout the list of form elements obviously increasing incrementally question_2, question_3 etc. The problem is that this is a bit messy. I'd like to use jQuery serializeArray but, to do this I would need to pass in an extra parameter. I need to pass the input value and the input id as this id is used in the data.
Is there a way I can achieve this using jQuery serializeArray()?
Example form markup:
<label>What is your gender?<span class="required"> *</span></label>
<input id="1" type="radio" name="question_1" value="Male"><label class="standard" for="1">Male</label><br>
<input id="2" type="radio" name="question_1" value="Female"><label class="standard" for="2">Female</label><br>
<label>How old are you?<span class="required"> *</span></label>
<input id="3" type="radio" name="question_2" value="Under 25"><label class="standard" for="3">Under 25</label<br>
<input id="4" type="radio" name="question_2" value="25-29"><label class="standard" for="4">25-29</label><br>
<input id="5" type="radio" name="question_2" value="30-39"><label class="standard" for="5">30-39</label><br>
<input id="6" type="radio" name="question_2" value="40-49"><label class="standard" for="6">40-49</label><br>
<input id="7" type="radio" name="question_2" value="50-59"><label class="standard" for="7">50-59</label><br>
<input id="8" type="radio" name="question_2" value="60+"><label class="standard" for="8">60+</label><br>
First of all, let me point out that this looks like a misuse of forms. If the name of the form element would be "answer1" instead of "question_1", and if your options would be named "q1_option" rather than "question_1", and if you accessed their values rather than their ids, you would be able to serialize the form in a simple one-liner, and, essentially, this is the meaning that name and value are intended to convey.
Having said that, $.serializeArray yields an array of key/value pairs. It's hard to see what you would want $.serializeArray to do in your specific scenario. If you want such an array, you could construct it yourself:
var keyValuePairs = [];
keyValuePairs.push({ name: 'answer1', value: $('input[name=question_1]:checked').val() })
var options = $('input[name^="question_"]:checked');
for(var i = 0; l = options.length; i < l; i++) {
keyValuePairs.push({
name: 'q' + i + '_option',
value: options.get(i).attr('id')
});
}
Given such an array, you could serialize it to a string like the one in your example, using
var data = $.param(keyValuePairs);

jQuery Validation Plugin Multiple Checkboxes

I am having some difficulty in using the jQuery Validator plugin. I have a list of checkboxes with different name attributes and I can't seem to figure out how to ensure that at least one of them has been checked. Everything that I find on Google seems to only work when the name attribute is the same.
Here is some sample code (updated):
<ul id="email_lists">
<li>
<input name="checkbox1" type="checkbox" /> List 1
</li>
<li>
<input name="checkbox2" type="checkbox" /> List 2
</li>
<li>
<input name="checkbox3" type="checkbox" /> List 3
</li>
<li>
<input name="checkbox4" type="checkbox" /> List 4
</li>
</ul>
I want to make sure that at least one of those is checked. Unfortunately, I cannot make the names the same as it is form that submits to a third-party email marketing application and it is expecting specific name attributes for these checkboxes.
Update
I am aware of how to do this using plain jQuery, but I would prefer to use the jQuery Validator plugin since that is how all of the other validation on the page is done.
I can group those checkboxes using jQuery by saying $('#email_lists li');, but I'm not really sure how to use something like that and tell the jQuery Validator plugin to use that as a group.
Assuming that you can give the checkboxes a class name (the jQuery needs something to work with):
<input class="validationGroupOne" name="checkbox1" type="checkbox" />
<input class="validationGroupOne" name="checkbox2" type="checkbox" />
<input class="validationGroupOne" name="checkbox3" type="checkbox" />
<input class="validationGroupOne" name="checkbox4" type="checkbox" />
You should be able to plug in the .validationGroupOne class-selector in place of the, usual, name attribute.
This was my solution :-)
Use:
<div id="list">
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
</div>
<input type="hidden" name="the_real_field_name" />
Then in jquery validate plugin block:
rules : {
chkbox: "required"
},
Then store the values as an array into a single hidden field like:
function updateInput() {
var allVals = [];
$('#list :checked').each(function() {
allVals.push($(this).val());
});
$('#the_real_field_name').val(allVals);
}
$(function() {
$('#list input').click(updateInput);
updateInput();
});

Categories

Resources