how to disable form submit and check the form - javascript

I have the following code. I need to see how many checkboxes have been checked in my form and if there are 4 or less submit the form and if there are more display an error and don't submit.
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
any help would be appreciated.

Your javascript looks correct. I think the only you should need to do is return false; on your if (totalChecked > 4) statement.
Edit: Here's the section of your javascript function to modify:
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}

Your function needs to return false to cancel the submission or true to proceed. That's why your onsubmit form attribute is set to "return XXX()" rather than just "XXX()"

As mentioned, you should return false from your check function to cancel the submit, and true if the check is okay.
How about something like this?
<html>
<head>
<title>Pizza Order Form</title>
</head>
<body>
<script>
function SetHiddenFieldValue() {
var totalChecked = 0;
var itemPrice = 5.99;
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var checks = document.getElementsByName('topping');
for (i = 0; i < checks.length; i++) {
if (checks[i].checked) {
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
}
else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
}
</script>
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<div id="toppings">
<input type="checkbox" name="topping" id="pepperoni" />Pepperoni
<input type="checkbox" name="topping" id="tomato" />Tomato
<input type="checkbox" name="topping" id="mushrooms" />Mushrooms
<input type="checkbox" name="topping" id="peppers" />Peppers
<input type="checkbox" name="topping" id="olives" />Olives
</div>
<input type="submit" name="my-add-button" value=" Add " />
</form>
</body>
</html>

Related

Multiple Checkbox Clear or Reset option Jquery

i want to consult issue about javascript jquery
i want this value > 20 && < 40 clear or reset option in jquery suggestion please.
It looks function error in javascript and function no clear and reset option. but function show display block wrong position .
<script>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function(e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()">
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()">
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()">
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);">
<input type="text" id="number" value="">
</form>
<a id="showdatacheckbox"></a>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function (e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
if (val > 20 && val < 40) {
$("input[type='checkbox']:checked").click();
}
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()" />
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()" />
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()" />
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);" />
<input type="text" id="number" value="" />
</form>
<a id="showdatacheckbox"></a>

how to output value from radio button

i am trying to output value of radio with innerHTML
But i do not succeed in this. What is going wrong?
<script>function changeText(){
var userInputgender = document.getElementByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
document.getElementById('output1').innerHTML = userInputgender;
break;
}
}
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<!-- here comes the output -->
<b id='output1'></b><br />
It's getElementsByName (plural).
function changeText() {
var userInputgender = document.getElementsByName('gender');
for (var i = 0, length = userInputgender.length; i < length; i++) {
if (userInputgender[i].checked) {
document.getElementById('output1').innerHTML = userInputgender[i].value;
break;
}
}
return false;
}
jsFiddle example
And you probably want the value (userInputgender[i].value;) returned to your div.
You could use jquery, it's much better. Look at this example:
HTML:
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<input id="button" type="button" value="Submit" />
<b id='output1'></b>
JS:
$("#button").click(function(){
var $name = $('input[name=gender]:checked').val();
$("#output1").text($name);
});
http://jsfiddle.net/LZWau/1/
<script type="text/javascript">
function changeText()
{
//get your 2 radio buttons
var userInputgender = document.getElementsByName('gender');
//loop on the buttons you found
for(var i=0;i<userInputgender.length;i++)
{
//is the button checked?
if(userInputgender[i].checked)
{
//fill the result element with the button value
document.getElementById('output1').innerHTML = userInputgender[i].value;
}
}
//return false so the form won't commit
return false;
}
</script>
<form method="get" onsubmit="return changeText()">
<input type="radio" name="gender" id="male" value="man" />Man
<input type="radio" name="gender" id="female" value="woman" />Woman<br />
<br /><br />
<input type="submit" value="Submit" />
</form>
<b id='output1'></b><br />
</script>
http://jsfiddle.net/ayy28/4/
var form = document.forms[0];
var userInputsgender = document.getElementsByName('gender');
form.addEventListener('submit', function(evt){
evt.preventDefault();
for (var i = 0, length = userInputsgender.length; i < length; i++) {
if (userInputsgender[i].checked) {
document.getElementById('output1').innerHTML = userInputsgender[i].value;
break;
}
else {
document.getElementById('output1').innerHTML = 'No gender was selected!';
}
}
});

auto search with checkbox inside textbox from databases

I can able to load value from databases to text-box...so now named as auto..from this i want to create a auto search with multiple check box to select multiple value in text-box java script...its possible ...??
<form name="form1">
<input type="checkbox" name="checkboxname" value="a">
<input type="checkbox" name="checkboxname" value="b">
<input type="checkbox" name="checkboxname" value="c">
</form>
<form name="form2">
<input type="text" name="textname">
</form>
var textbox = document.getElementsByName("textname")[0];
var checkboxes = document.getElementsByName("checkboxname");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = (function(chk){
return function() {
var value = "";
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
if (value === "") {
value += checkboxes[j].value;
} else {
value += "," + checkboxes[j].value;
}
}
}
textbox.value = value;
}
})(checkbox);
}
Try this,
<form name="form1" class="form_chk">
<input type="checkbox" name="checkboxname" value="a" class="chk_box">a
<input type="checkbox" name="checkboxname" value="b" class="chk_box">b
<input type="checkbox" name="checkboxname" value="c" class="chk_box">c
</form>
$( "#txt_search" ).blur(function(e) {
var $search = $(e.currentTarget),
search_str = $search.val().toLowerCase(), $chk,
$chk_ele = $('.chk_box').filter(function(index, chk){
if($(chk).val().toLowerCase().search(search_str) !== -1){
return $(chk);
}
});
$('.chk_box').prop('checked', false);
$chk_ele.prop('checked', true);
});
See the output : http://jsfiddle.net/J7dUz/

Check sum of inputs before submit

I need some help: I have the following form:
<form id="myForm" method="post" action="?action=agc">
<input type="hidden" name="start_date" value="<?= $_POST['start_date'] ?>" />
<input type="hidden" name="end_date" value="<?= $_POST['end_date'] ?>" />
<input type="hidden" name="c_name" value="<?= $_POST['c_name'] ?>" />
<input type="hidden" name="cluster" value='<?= $abn_cluster[0] ?>' />
<input type="hidden" name="abn" value="abn" />
Add percent <br /><br />
ABN percent<br />
<input type="text" name="poll[option][0][percent]" class="toAdd"> <input type="text" name="poll[option][0][name]" value="<?= $_POST['c_name'] ?>_0_"> <input type="checkbox" class="optionBox" value="True" name="poll[option][0][control_sample]" /><br />
<script>
var optionNumber = 1;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
var newOption2 = document.createElement("input");
var newOption3 = document.createElement("input");
var newLabel = document.createElement("label");
var newContent = document.createTextNode(" ");
var newContent2 = document.createTextNode(" ");
newOption.name = "poll[option]["+optionNumber+"][percent]";
newOption.type = "text";
theForm.appendChild(newOption);
theForm.appendChild(newContent);
newOption2.name = "poll[option]["+optionNumber+"][name]";
newOption2.type = "text";
newOption2.value = "<?= $_POST['c_name'] ?>_"+optionNumber+"_"
theForm.appendChild(newOption2);
theForm.appendChild(newContent2);
newOption3.name = "poll[option]["+optionNumber+"][control_sample]";
newOption3.type = "checkbox";
newOption3.className = "optionBox";
newOption3.value = "True"
theForm.appendChild(newOption3);
theForm.appendChild(document.createElement("br"));
optionNumber++;
}
</script>
</p>
</div>
<div class="modal-footer" id="appendform">
<button type="submit" class="btn btn-primary">Continue</button>
</form>
Now because some of the inputs are generated on request, I have no idea how to check the sum of the(.toAdd). And I basically need to make sure that it's equal to 100 before submitting. What would be a solution to my problem? Thanks.
Try
<form id="myForm" method="post" action="iap_crm_campaign.php?action=abngamecampaign" onsubmit="return validate()">
Then
function validate(){
var sum = 0;
for(var i = 0; i < optionNumber; i++){
sum += parseFloat(document.getElementsByName('poll[option][' + i + '][percent]')[0].value);
}
if( sum == NaN || sum != 100){
alert('Sum of percentage must be 100');
return false;
}
}
Demo: Fiddle
var total = 0;
var toAdds = document.getElementsByClassName("toAdd");
for (var i = 0; i < toAdds.length; i++) {
total += parseInt(toAdds[i].value, 0);
}
if (total == 100) {
// OK
} else {
// not OK
}
Also, your code for adding new options needs to set the class:
newOption.className = "toAdd";
you can use jquery
$(".toAdd").length
or in simple js
var myInputs= document.getElementsByTagName('input');
var noOfInputs =myInputs.length;
well this will give you the count of i/p elements through loop, for summing the values...
var sum;
$(".toAdd").each(function() {
sum=sum+$(this).val();
});

How to make different calculations based on the same radio button values?

I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}

Categories

Resources