Submit value of a checkbox through javascript - javascript

I am trying to submit values of a form through javascript it contains both text and two checkboxes.
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $(".relocation").val();
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation[]" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation[]" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
r_two.php
<?
$preffered_loc = $_POST['preffered_loc'];
$relocation = $_POST['relocation'];
?>
i am able to save the first value but i am not able to save relocation value, can anyone tell how i can save relocation. Important point here is that user can select both checkboxes also
The issue is that $relocation is picking only value yes even if i select 2nd selectbox. can anyone please correct my code

try this.
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = $("#relocation").is(":checked");
var relyn = "";
if(relocation){
relyn = "Yes";
}else{
relyn = "No";
}
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relyn },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
alert("{ preffered_loc: "+preffered_loc+",relocation: "+relyn+" }");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" id="relocation" />
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
As Satpal said:
You don't need two checkbox, maybe you want a radio button, but one checkbox can be checked = yes, not checked = no. I removed one of them.
You don't have an ID relocation. I changed it.
With the jQuery is(":checked") you get a true or false so I parse it to a Yes or No, following your code.

Since its a checkbox and not a radio user can have multiple selections, for eg:
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="checkbox" name="relocation[]" class="relocation" value="Both" >
try using the :checked selector,
$( ".relocation:checked" ).each(function(i,v){
alert(v.value)
});
Demo here

I think you should use class for the check-boxes instead of id, because id must be unique for each field. You should try this:
<form id="myForm2" method="post" style="margin-left: -10%;">
<input type="text" class="form-control" id="preffered_loc" name="preffered_loc">
<input type="checkbox" name="relocation[]" class="relocation" value="Yes">
<input type="checkbox" name="relocation[]" class="relocation" value="No" >
<input type="button" id="submitFormData2" onclick="SubmitFormData2();" value="Submit" />
</form>
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = '';
var sap = '';
$( ".relocation" ).each(function() {
if($( this ).is(':checked')){
relocation = relocation+''+sap+''+$( this ).val();
sap = ',';
}
});
alert(rel);
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>

Here is a sample code for your reference
<form id="myForm" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone No:<input name="phone" id="phone" type="text" /><br />
Gender: <input name="gender" type="radio" value="male">Male
<input name="gender" type="radio" value="female">Female<br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
function SubmitFormData() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var gender = $("input[type=radio]:checked").val();
$.post("submit.php", { name: name, email: email, phone: phone, gender: gender },
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}

You couldn't select the checkbox elements at all because you weren't including the [] in the selector. You can either escape the brackets as described in this SO Q/A or simply remove the brackets (the example code below does the latter)
I'd suggest using radio buttons as the user can immediately see what the options are. (Have a third option for both)
The code below uses checkboxes and puts all selected options into an array that gets passed along. This will allow the user to use both options
<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = [];
$(".relocation:checked").each(function () {
relocation.push ($this.vak ();
}); // :checked is provided by jquery and will only select a checkbox/radio button that is checked
$.post("r_two.php", { preffered_loc: preffered_loc,relocation: relocation },
function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
And don't forget to remove [] from the checkboxes class.

<script>
function SubmitFormData2() {
var preffered_loc = $("#preffered_loc").val();
var relocation = {};
$('.relocation').each(function(index) {
if ($(this).is(':checked')) {
relocation[index] = $(this).val();
}
});
relocation = JSON.stringify(relocation);
$.post("r_two.php", { preffered_loc: preffered_loc, relocation: relocation }, function(data) {
$('#results').html(data);
$('#myForm2')[0].reset();
});
}
</script>
Variable 'relocation' must be an object to contain multiple values, like you said a user can select both YES and NO. And change the checkbox class from relocation[] to relocation.

Related

How to concatenate form array inputs before submission?

Example code:
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
On form submission the URL should look like:
http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty
What I am observing now is,
http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty
The serialize() or serializeArray() is not working in this case. Any ideas?
You could grab the result of .serializeArray and transform it into the desired format:
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serializeArray();
var dataByKey = data
.reduce((result, entry) => {
var name = entry.name.replace(/\[\]$/, '');
(result[name] || (result[name] = [])).push(entry.value);
return result;
}, {});
Object.keys(dataByKey)
.forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
console.log(dataByKey);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<fieldset>
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
</fieldset>
<fieldset>
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
</fieldset>
<input type="submit" />
</form>
If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/
<form id="myForm" method="get">
<input type="checkbox" name="anythingOne[]" value='one'>1
<input type="checkbox" name="anythingOne[]" value='two'>2
<input type="checkbox" name="anythingOne[]" value='three'>3
<input type="checkbox" name="otherThingTwo[]" value='Forty'>40
<input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
<input type="submit" />
</form>
JS:
const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
e.preventDefault();
let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});
In case, you are allowed to change html, here is a solution using hidden fields.
function updateChecks() {
$.each(['anythingOne', 'otherThingTwo'], function(i, field) {
var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
return this.value;
}).get().join(',');
$('input[type=hidden][name=' + field + ']').val(values);
});
}
$(function() {
$('form').on('submit', function(e) {
updateChecks();
});
updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="hidden" name="anythingOne" value='' />
<input type="hidden" name="otherThingTwo" value='' />
<input type="checkbox" data-for="anythingOne" value='one' checked='' />
<input type="checkbox" data-for="anythingOne" value='two' />
<input type="checkbox" data-for="anythingOne" value='three' checked='' />
<input type="checkbox" data-for="otherThingTwo" value='Forty' />
<input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>
You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:
$('form').submit(function() {
var queryString = $(this).serializeArray()
.reduce(function(transformed, current) {
var existing = transformed.find(function(param) {
return param.name === current.name;
});
if (existing)
existing.value += (',' + current.value);
else
transformed.push(current);
return transformed;
}, [])
.map(function(param) {
return param.name + '=' + param.value;
})
.join('&');
var action = $(this).prop('action');
var delimiter = (~action.indexOf('?')) ? '&' : '?';
$(this).prop('action', action + delimiter + queryString);
// Only for display result. Remove on real page.
var url = $(this).prop('action');
console.log(url);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
<input type="checkbox" name="anythingOne" value='one'>
<input type="checkbox" name="anythingOne" value='two'>
<input type="checkbox" name="anythingOne" value='three'>
<input type="checkbox" name="otherThingTwo" value='Forty'>
<input type="checkbox" name="otherThingTwo" value='Fifty'>
<button type="submit">Show target URL</button>
</form>
The latest 3 lines are used only to prevent the form sending and display resulted URL.
Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.
You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.
$(document).ready(function(){
$("button").click(function(){
/* concatenate anythingOne form*/
//collect anythingOne input
var joined_serialized = []
var anythingOne = [];
$.each($("input[name='anythingOne[]']:checked"), function(){
anythingOne.push($(this).val());
});
//join otherThingTwo input
var anythingOne_serialized = "";
if(anythingOne.length > 0){ //only collect if checked
anythingOne_serialized = "anythingOne=" + anythingOne.join(",");
joined_serialized.push(anythingOne_serialized)
}
/* concatenate otherThingTwo form*/
//collect otherThingTwo input
var otherThingTwo = []
$.each($("input[name='otherThingTwo[]']:checked"), function(){
otherThingTwo.push($(this).val());
});
//join otherThingTwo input
var otherThingTwo_serialized = "";
if(otherThingTwo.length > 0){ //only collect if checked
otherThingTwo_serialized = "otherThingTwo=" + otherThingTwo.join(",");
joined_serialized.push(otherThingTwo_serialized)
}
/*join different form names*/
var joined_serialized = joined_serialized.join("&")
if(joined_serialized.length == 1){ //remove last & if only one form is checked
joined_serialized = joined_serialized.slice(0, -1)
}
/*concatenated forms with website*/
var result = "http://some-website.tld/action?"+joined_serialized
console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>
<button>submit<button/>

jQuery checkbox script giving odd results

Script is supposed to check all hidden checkboxes when the main checkbox attribute is checked as TRUE.
If it's left unchecked, or if user checks/unchecks, the same value should be applied for the hidden attributes.
It works fine 90% of times, but it seems in some cases (not sure how yet) it doesnt work, and some results come in where user has main checkbox as TRUE but all others as FALSE, and vice-versa.
Why does it happen?
<script>
$(function() {
var marketingMAIN= $("input[type='checkbox'][name='marketingMAIN']");
var marketingPhone = $("input[type='hidden'][name='marketingPhone']");
var marketingRobo = $("input[type='hidden'][name='marketingRobo']");
var marketingSMS = $("input[type='hidden'][name='marketingSMS']");
var marketingEmail = $("input[type='hidden'][name='marketingEmail']");
var marketingIM = $("input[type='hidden'][name='marketingIM']");
var marketingPush = $("input[type='hidden'][name='marketingPush']");
var marketingPaperMail = $("input[type='hidden'][name='marketingPaperMail']");
marketingMAIN.on('change', function()
{
if ($(this).val() == "TRUE") {
marketingPhone.prop('checked',true);
marketingPhone.val('TRUE');
marketingRobo.prop('checked',true);
marketingRobo.val('TRUE');
marketingSMS.prop('checked',true);
marketingSMS.val('TRUE');
marketingEmail.prop('checked',true);
marketingEmail.val('TRUE');
marketingIM.prop('checked',true);
marketingIM.val('TRUE');
marketingPush.prop('checked',true);
marketingPush.val('TRUE');
marketingPaperMail.prop('checked',true);
marketingPaperMail.val('TRUE');
} else {
marketingPhone.prop('checked',false);
marketingPhone.val('FALSE');
marketingRobo.prop('checked',false);
marketingRobo.val('FALSE');
marketingSMS.prop('checked',false);
marketingSMS.val('FALSE');
marketingEmail.prop('checked',false);
marketingEmail.val('FALSE');
marketingIM.prop('checked',false);
marketingIM.val('FALSE');
marketingPush.prop('checked',false);
marketingPush.val('FALSE');
marketingPaperMail.prop('checked',false);
marketingPaperMail.val('FALSE');
}
});
});
</script>
The hidden attributes are marked as follows:
<input type="hidden" name="marketingPhone" value=""/>
<input type="hidden" name="marketingRobo" value=""/>
<input type="hidden" name="marketingSMS" value=""/>
<input type="hidden" name="marketingEmail" value=""/>
<input type="hidden" name="marketingIM" value=""/>
<input type="hidden" name="marketingPush" value=""/>
<input type="hidden" name="marketingPaperMail" value=""/>
The value won't change for a checkbox unless you specifically change it. Try using is() like in this answer.
Instead of checking the visible checkbox's value in your change listener like this:
if ($(this).val() == "TRUE") {
Check its checked attribute:
if ($(this).is(":checked")) {
Here's a working example:
$(function() {
var marketingMAIN = $("input[type='checkbox'][name='marketingMAIN']");
var marketingPhone = $("input[name='marketingPhone']");
var marketingRobo = $("input[name='marketingRobo']");
var marketingSMS = $("input[type='hidden'][name='marketingSMS']");
var marketingEmail = $("input[type='hidden'][name='marketingEmail']");
var marketingIM = $("input[type='hidden'][name='marketingIM']");
var marketingPush = $("input[type='hidden'][name='marketingPush']");
var marketingPaperMail = $("input[type='hidden'][name='marketingPaperMail']");
marketingMAIN.on('change', function() {
if ($(this).is(":checked")) {
marketingPhone.prop('checked', true);
marketingPhone.val('TRUE');
marketingRobo.prop('checked', true);
marketingRobo.val('TRUE');
marketingSMS.prop('checked', true);
marketingSMS.val('TRUE');
marketingEmail.prop('checked', true);
marketingEmail.val('TRUE');
marketingIM.prop('checked', true);
marketingIM.val('TRUE');
marketingPush.prop('checked', true);
marketingPush.val('TRUE');
marketingPaperMail.prop('checked', true);
marketingPaperMail.val('TRUE');
} else {
marketingPhone.prop('checked', false);
marketingPhone.val('FALSE');
marketingRobo.prop('checked', false);
marketingRobo.val('FALSE');
marketingSMS.prop('checked', false);
marketingSMS.val('FALSE');
marketingEmail.prop('checked', false);
marketingEmail.val('FALSE');
marketingIM.prop('checked', false);
marketingIM.val('FALSE');
marketingPush.prop('checked', false);
marketingPush.val('FALSE');
marketingPaperMail.prop('checked', false);
marketingPaperMail.val('FALSE');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="marketingMAIN" value="" />
<input type="hidden" name="marketingPhone" value="" />
<input type="hidden" name="marketingRobo" value="" />
<input type="hidden" name="marketingSMS" value="" />
<input type="hidden" name="marketingEmail" value="" />
<input type="hidden" name="marketingIM" value="" />
<input type="hidden" name="marketingPush" value="" />
<input type="hidden" name="marketingPaperMail" value="" />
Change any of the checkboxes from type="hidden" to type="checkbox" and you can see them check and uncheck depending on what your main checkbox does.

How to make one of three inputs type button requierd required

My problem is that I have one form with some fields and three inputs type button, they all represents one message. I want to make chooseing one of three messages required. My code is bellow:
<input id="poruka1" type="button" class="hm_datumibtn poruka" name="poruka1" value="Pored mene, sve želje " >
<input id="poruka2" type="button" class="hm_datumibtn poruka" name="poruka2" value="Pored sebe, sve želje " >
<input id="poruka3" type="button" class="hm_datumibtn poruka" name="poruka3" value="Pored tebe, sve želje " >
Do you have any idea how can I solve this kind of problem?
<script>
function upis(){
//var datum = $(this).find('.datum').val();
//var poruka = $(this).find('.poruka').val();
//var poruka = $(this).attr('value');
if (poruka_forma.poruka1.value == '' && poruka_forma.poruka2.value == ''&& poruka_forma.poruka3.value == '') {
alert('You have to choose message.');
return false;
}
else {
myForm.submit();
}
var ime = document.getElementById("ime").value;
var ime_slavljenik = document.getElementById("ime_slavljenik").value;
var elementsdate = document.getElementsByClassName("selected_date");
var datum = elementsdate[0].value;
var elements = document.getElementsByClassName("selected");
var poruka = elements[0].value;
//var poruka = document.getElementById("poruka").value;
//var datum = document.getElementById("datum").value;
//var poruka = document.getElementById("poruka").value;
//var email = document.getElementById("email").value;
//var dataString = "ime="+encodeURIComponent(ime)+"&ime_slavljenik="+encodeURIComponent(ime_slavljenik);
$.ajax({
type:"post",
url: "upis.php",
cashe: false,
//data: dataString+'&datum='+datum+'&poruka='+poruka,
data: {ime:ime,ime_slavljenik:ime_slavljenik,datum:datum, poruka:poruka},
success: function(data){
//window.alert(data);
document.getElementById("placefortableanketa").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
I think you might want to use <input type="radio" /> instead. Example:
<form>
<input type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>
You can add required attributes to make them required. Also, adding checked attributes will make a radio button selected by default.
You can also use <label> with for attribute. When that label is clicked, it selects a radio button that it refers to by id in its for attribute.
Edit: I saw your comment that you don't want to use radio buttons because of the design. You can actually hide the radio buttons, and just use <label> with for attributes. Example:
<style>
#radio_btn_1:checked + label{background-color:red;}
#radio_btn_2:checked + label{background-color:red;}
#radio_btn_3:checked + label{background-color:red;}
</style>
<form>
<input style="display:none;" type="radio" id="radio_btn_1" name="radio_btn" value="choice_1" required="required" checked="checked" /><label for="radio_btn_1">Choice 1</label><br />
<input style="display:none;" type="radio" id="radio_btn_2" name="radio_btn" value="choice_2" required="required" /><label for="radio_btn_2">Choice 2</label><br />
<input style="display:none;" type="radio" id="radio_btn_3" name="radio_btn" value="choice_3" required="required" /><label for="radio_btn_3">Choice 3</label><br />
</form>

Javascript: How to check if each input value is duplicated to another input value

So i have a dynamic input field came from append with different class name and names, i want to check each of input field value already exist or duplicate.
This would look like
The first criteria_name is default and the others are appendend.
<input type="text" name="criteria_name" class="criteria_name">
<input type="text" name="criteria_name2" class="criteria_name2">
<input type="text" name="criteria_name3" class="criteria_name3">
<input type="text" name="criteria_name4" class="criteria_name4">
<input type="text" name="criteria_name5" class="criteria_name5">
I am trying to check each one of those if there is no duplicated else proceed.
var critname_arr = [];
var input_check;
var crit_name_of_first = $('input.criteriaNames').val();
var acappended = append_crit_header+1;
var count_to = 0;
for(var ab = 2; ab<=acappended; ab++){
var crit_arr;
if(crit_name_of_first == $('input.criteria_each_name'+ab+'').val()){
alert("Criteria cannot be duplicate");
return false;
}else{
input_check = $('input.criteria_each_name'+ab);
input_check.each(function(){
crit_arr = $.trim($(this).val());
});
critname_arr.push(crit_arr);
}
if($('input.criteria_each_name'+ab+'').val() == critname_arr[count_to]){
alert('criteria cannot be duplicate');
return false;
}
count_to++;
}
console.log(critname_arr);
Here is just an example of how you can do it. In the fiddle change one of the values to one that is already in another field (make a duplicate value) to see it do something. If there are no duplicates, it will not do anything. Click the "Button" text to run the duplicate check:
jsFiddle: https://jsfiddle.net/o52gjj0u/
<script>
$(document).ready(function(){
$('.ter').click(function(e) {
var stored = [];
var inputs = $('.criteria_name');
$.each(inputs,function(k,v){
var getVal = $(v).val();
if(stored.indexOf(getVal) != -1)
$(v).fadeOut();
else
stored.push($(v).val());
});
});
});
</script>
<!-- Just use an array name for the input name and same class name as well -->
<div class="ter">Button</div>
<input type="text" name="criteria_name[]" class="criteria_name" value="1" />
<input type="text" name="criteria_name[]" class="criteria_name" value="2" />
<input type="text" name="criteria_name[]" class="criteria_name" value="3" />
<input type="text" name="criteria_name[]" class="criteria_name" value="4" />
<input type="text" name="criteria_name[]" class="criteria_name" value="5" />

Pass jQuery array value on submit as hidden input

On button press the following code will display a message with values collected from all checkboxes. But I want to pass these values (returned by function) as hidden input on submit.
<form action="script.php" method="post">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="button" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('btntest').onclick = function(){
var selchb = getSelectedChbox(this.form);
alert(selchb);
}
//-->
</script>
I've seen guys like you trying to code my router interface, so I'll help out.
give your form an id cause you'll need it later
<form action="script.php" method="post" id="the_form">
add the hidden input in the form
<input type="hidden" name="values" id="values" value="" />
the button in the form matures to a real submit (amazing)
<input type="submit" ...
your "getSelectedChbox()" function is amazing; don't change anything there, just wanted to give you congratulations for it, it's a great function
now, where it says document.getElementById('btntest').onclick - get rid of all that and add this code instead; this code will do the rest.
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
Or simply copy-paste this whole thing in a file called script.php:
<?php echo var_dump(isset($_POST['values']) ? $_POST['values'] : 'Submit first.'); ?>
<form action="script.php" method="post" id="the_form">
<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>
<input type="hidden" name="values" id="values" value="" />
<input type="submit" value="Click" id="btntest" />
</form>
<script type="text/javascript"><!--
function getSelectedChbox(frm) {
var selchbox = [];
var inpfields = frm.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)
selchbox.push(inpfields[i].value);
}
return selchbox;
}
document.getElementById('the_form').onsubmit = function(){
var selchb = getSelectedChbox(this);
var values = selchb.join(', ');
if(!values.length){
alert('There was an error. You have to select some checkboxes. ');
return false;
}
document.getElementById('values').value = values;
if(!confirm(" Are you interested in submitting this form now? If not, click accordingly. "))
return false;
}
//-->
</script>
Have fun.

Categories

Resources