How do I write JavaScript that validates input across multiple forms? - javascript

I am attempting to write JavaScript that traverses multiple HTML forms, checks an input for a given value on edit, then enables/disables the submit button for that form based on the input value.
I have a very simple example script, which overrides the onclick function of checkboxes, to test the flow of my code.
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<form>
<input type="checkbox" />
<input type="submit" disabled="disabled" />
</form>
<script type="text/javascript">
forms = document.getElementsByTagName("form");
for(i=0; i<forms.length; i++)
{
inputs = forms.item(i).getElementsByTagName("input");
inputs.item(0).onclick = function()
{
if(this.checked)
inputs.item(1).removeAttribute("disabled");
else
inputs.item(1).setAttribute("disabled","disabled");
}
}
</script>
What I expect to happen: the checkboxes change the value of the submit button in the same form.
What actually happens: all the checkboxes change the value of the submit button in the last form.
The actual code will be somewhat smarter, but I want to understand the flow of JavaScript code before progressing onto something more complex.
Thanks in advance!

Try something like this:
document.body.onchange = function(e) {
// this delegates all the way to the body - if you have a more specific
// container, prefer using that instead.
e = e || window.event;
var t = e.srcElement || e.target;
if( t.nodeName == "INPUT" && t.type == "checkbox") {
// may want to add a className to the checkboxes for more specificity
t.parentNode.getElementsByTagName('input')[1].disabled = !t.checked;
}
};
The reason you are seeing the behaviour you're getting is because inputs' value is not fixed, you are repeatedly re-assigning it to the next form's elements, ultimately resulting in the last one.

Related

Change attribute value for event only

I have this basic form:
jQuery(document).ready(function($) {
$('#btn').click(function() {
var form = document.getElementById('form');
form.setAttribute('action', 'export.php');
form.submit()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="get.php" id="form">
<div>
<label for="date">From</label>
<input type="date" name="from-date" id="date" />
</div>
<div>
<label for="date">To</label>
<input type="date" name="to-date" id="date" />
</div>
<div>
<input type="checkbox" name="flags[new]" /> New
<input type="checkbox" name="flags[updated]" /> Updated
<input type="checkbox" name="flags[existing]" /> Existing
</div>
<div>
<input type="submit" />
</div>
<div>
<button type="button" id="btn">
<span>Export</span>
</button>
</div>
</form>
This works as (near) expected. However, I then clicked on the submit input and it tried going to export.php. For some reason my brain was telling me that this is incorrect behaviour, but I get that I've changed the attribute value within the DOM and thus, anything post-clicking the export button will render the attribute value (until I refresh).
I'm aware that I can do another event handler to reset the attribute value, but I feel like that's counter-intuitive, is there something in JS/jQuery that allows me to "toggle" an attribute for the event only? Or do I have to make-do with a hard reset?
TL;DR
Is there a way to temporarily set an attribute within an event?
Try something like this:
jQuery(document).ready(function($) {
$('#btn').click(function() {
let form = document.getElementById('form');
//Save the current attr
let currentAttr = form.getAttribute('action');
form.setAttribute('action', 'export.php');
form.submit();
//Reset the previous attr
form.setAttribute('action', currentAttr);
})
})
You actually save the current attr, submit the form and then set the attribute to the original one.
Hope it solved your issue!

How to submit 0 if checkbox is unchecked and submit 1 if checkbox is checked in HTML [duplicate]

This question already has answers here:
Posting both checked and unchecked checkboxes
(3 answers)
POST unchecked HTML checkboxes
(44 answers)
Closed 1 year ago.
How to submit value 1 if a checkbox in a checkbox array is checked, and submit 0 if it's unchecked? I tried this but no luck. I am trying to grab this array in a php array when the form is submitted. Please help!
<input id = 'testName0' type = 'checkbox' name = 'check[0]' value = '1' checked>
<input id='testNameHidden0' type='hidden' value='0' name='check[0]'>
<input id = 'testName1' type = 'checkbox' name='check[1]' value = '1' unchekced>
<input id='testNameHidden1' type='hidden' value='0' name='check[1]'>
<input type = 'submit' value = 'Save Changes'>
>
<script>
if(document.getElementById('testName0').checked){
document.getElementById('testNameHidden0').disabled = true;
}
</script>
<script>
if(document.getElementById('testName1').checked){
document.getElementById('testNameHidden1').disabled = true;
}
</script>
Simplest one, no javascript required, just put a hidden input before the checkbox:
<input type="hidden" name="check[0]" value="0" />
<input type="checkbox" name="check[0]" value="1" />
Inputs need to have the same name. If the checkbox is checked then value 1 will be submitted, otherwise value 0 from the hidden input.
Your case javascript solution, no hidden inputs needed:
<script type="text/javascript">
// when page is ready
$(document).ready(function() {
// on form submit
$("#form").on('submit', function() {
// to each unchecked checkbox
$(this + 'input[type=checkbox]:not(:checked)').each(function () {
// set value 0 and check it
$(this).attr('checked', true).val(0);
});
})
})
</script>
<form method="post" id="form">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
PHP solution, no hidden inputs needed:
<?php
// if data is posted, set value to 1, else to 0
$check_0 = isset($_POST['check'][0]) ? 1 : 0;
$check_1 = isset($_POST['check'][1]) ? 1 : 0;
?>
<form method="post">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
EDIT: the javascript solution is not valid anymore as of jquery 1.6. Based on this, a more proper solution is the following:
<script type="text/javascript">
// when page is ready
$(document).ready(function() {
// on form submit
$("#form").on('submit', function() {
// to each unchecked checkbox
$(this).find('input[type=checkbox]:not(:checked)').prop('checked', true).val(0);
})
})
</script>
<form method="post" id="form">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
A better solution that solved this for me.
Problem: Both the hidden and the checked were sending to my server.
Solution:
if len(key) == 1 {
value = false
} else {
value = true
}
This way, if len(key) is 1 I know that only the hidden field was being send. Any other scenario means that the box is checked. Simple and easy.
Well I have a much more simple code that worked well for me:
<input type="checkbox" value="true" id="checkBox">
Then the JQuery code:
var checkBoxValue = $('#checkBox').is(':checked')?$('#checkBox').val():false
I used a ternary operator to set the value on checked and unchecked condition.

Javascript onsubmit with cgi action?

I have a html form and have a cgi script running on the action and then I have a javascript onsubmit function that should check if the radio button was filled out otherwise it wont submit.
<script>
function checkscript()
{
.... check if a radio button was clicked otherwise dont submit.
}
</script>
<form action="default.cgi" method="post" onsubmit="return checkscript()" enctype=
"application/x-www-form-urlencoded">
<h1>Choose</h1>
<p><input type="radio" name="Radio" value="1" /><font size="5"
color="#0033CC">Instant Psychology</font><br />
<br />
<input type="radio" name="Radio" value="2" /><font size="5"
color="#CC0000">Instant Geography</font><br />
<br />
<form/>
Can I do this in a Javascript function in the html file or do I need to do that in the cgi script?
The following script works in all browsers. First, gets the inputs on the page, then loops through each checking the name attribute for Radio. As soon as it finds one Radio input that is checked (selected), it returns true which will submit the form. If, however, none of the inputs are checked (selected), the script returns false and prevents a submission.
function checkscript()
{
var inputs = document.getElementsByTagName("input");
for (var i=0, l=inputs.length; i<l; i++) {
if (inputs[i].name === "Radio" && inputs[i].checked) return true;
}
return false;
}
if you can use jquery, you do this
function checkscript(){
if($('#radio-button').is(':checked')) return true;
else return false;
}
and yes, you can just place it in your html file.
Hope this helps.

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.

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources