I have group of check-boxes and corresponding text-boxes with them. I can get each checkbox one by one, but how do I get the group of textboxes so I can validate them?
Here is my javascript code below:
function validate_orderform(proform)
{
var flag=0;
for (var i = 0; i < proform.chk.length; i++) {
if (proform.chk[i].checked && proform.quant[i].value=="") {
flag=1;
}
}
if(flag==1){
return false;
}
return true;
}
and my html code:
<td><input type="checkbox" id="chk1" name="chk"></td>
<td><input type="text" size="10" id="quant1" name="quant1"></td>...and so on
If name of textboxes are different then you can access all textboxes by
var txtObjList = document.getElementsByTagName("input");
for(var i=0; i < txtObjList.length; i++){
if(txtObjList[i].getAttribute("type") == "text" && this.value != ""){
// success for i+1 textbox
}
}
Or you can give common class name to all textboxes and then can access by
var txtObjList = document.getElementsByClassName("classname");
for(var i=0; i < txtObjList.length; i++){
if(this.value != ""){
// success for i+1 textbox
}
}
Remember by using javascript library such as jquery, prototype your work will be simpler.
There are a couple of methods you could use, you could use document.getElementsByTagName to retrieve all of the input elements, check their type etc... It works but it's slow and potentially expensive depending on how complex your form is.
If you have a group of checkboxes and each one has it's own text box then you could group them, so add a common name to each type, e.g.
Entry 1:
<input type="checkbox" id="chk1" name="chk"/>
<input type="text" id="quant1" name="quant"/>
Entry 2:
<input type="checkbox" id="chk2" name="chk"/>
<input type="text" id="quant2" name="quant"/>
Then you can use the document.getElementsByName method, so in this instance the following would retrieve a collection of 2 objects for you're text boxes:
var myTextBoxes = document.getElementsByName("quant");
Related
Im trying to write a validation for 2 groups of fields. I have 6 inputs, 3 for text name and 3 more for id number... the validation should do this "if input name="RE_SignedByID" has an input type name="RE_SignedByName", then other inputs name="RE_SignedByID", should NOT contain the same name="RE_SignedByName" More easy explanation... one ID number should have only one Person Name (Id number is unique for one person name). What can I use for that? Should I map() all the inputs?
Those are my inputs:
<div id="signedBy" class="clearfix">
<label>Signer, person ID & name</label>
<span id="signedByID" class="ids half">
<input type="text" name="RE_SignedByID" placeholder="personID, person1" data-validate="" tabindex="101" required>
<input type="text" name="RE_SignedByID" placeholder="personID, person2" data-validate="" tabindex="103">
<input type="text" name="RE_SignedByID" placeholder="personID, person3" data-validate="" tabindex="105">
</span>
<span class="names half">
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" required>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="104">
<input type="text" name="RE_SignedByName" placeholder="name, person3" tabindex="106">
</span>
</div>
I guess it should also be an "on change" function? or can I make the validation on click? Some ideas...? Im actually compleatley lost here...
Thanks in advance!!!
Maybe use different class names for all 3 of them to make them unique?
<input class="name1">
<input class="name2">
<input class="name3">
I'm not sure what you mean but if you want to make the input types unique and not call them all when you write class="names half", then you should give them all unique class names.
So from my understanding you don't want multiple fields to have the same value.
My approach would be this:
let inputTimeout = null; //set an empty timeout object
let vars = [null, null, null, null]; // create an array containing as many nulls as you have inputs
$('.nameInput').on('keyup', function(){
let self = $(this);
clearTimeout(inputTimeout); //clear the timeout
inputTimeout = setTimeout(function(){ //set a timeout to check whether there is a dupe after the user has stopped typing
if (vars.indexOf(self.val()) == -1){ //check if the vals array contains the newly entered string
vars[self.attr('data-inputnum')] = self.val(); //insert the value into the array
}else{
//handle duplicates here
}
}, 500); //500ms is a sensible value for end of user input, change it if users complain that your app is too fast/slow
});
You then just have to edit your HTML a bit so that all name inputs have a class in common (i used .nameInput) and have a data-inputnum attr.
This would look something like this:
<input type="text" name="RE_SignedByName" placeholder="name, person1" tabindex="102" class='nameInput' data-whichinput='0'/>
<input type="text" name="RE_SignedByName" placeholder="name, person2" tabindex="103" class='nameInput' data-whichinput='1'/>
<!--and so on-->
Of course, never rely on JavaScript verification alone, always also check inside your backend. However this would be out of scope for this answer.
Hi Thanks all for the help, made me realize a couple of things till I got the answer. This is my working code:
var valSignedID = $("[name=SignedByID]").map(function() {
return this.value.trim();
}).get();
var valOwnersID = $("[name=OwnersID]").map(function() {
return this.value.trim();
}).get();
valSignedID.sort();
valOwnersID.sort();
for (var i = 0; i < valSignedID.length - 1; i++) {
if (valSignedID[i] == valSignedID[i + 1] && valSignedID[i] != "") {
alert(" You can not have duplicated signers ID's");
return false;
// break;
}
}
for (var i = 0; i < valSingedName.length; i++) {
if (valSingedName[i] == valSingedName[i + 1] && valSingedName[i] != "") {
alert(valSingedName[i] + " should not have different ID");
//return false;
}
}
I'm using JavaScript to get value from the radio boxes to insert it to the database as a string. What I need is that I have more than 2 radio boxes. How would I make use of Javascript to add the values to my database?
Here is my code:
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='Sentinel' checked="checked">
Sentinel GM
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardTrack'>
GuardTrack
</td>
<td>
<input type="radio" name="company_grp" class="largerCheckbox" value='GuardingProduct'>
Guarding Product
</td>
if (!document.frmAdd_Visit.company_grp[0].checked && !document.frmAdd_Visit.company_grp[1].checked && !document.frmAdd_Visit.company_grp[2].checked) {
alert("Please Select the company group does this client belong's to!");
form.company_grp.focus();
return false;
}
It's very tricky but I don't get the correct value. When I select the 3rd radio, it doesn't add to the database but instead it reloads the page.
you can use jquery to get value form radio box
$(document).ready(function(){
$('input[name="company_grp"]:checked').val();
});
The jquery code below returns the value:
$('input[name=company_grp]:checked').val()
can use radio type checked as $(':radio:checked')
var selectedvalue;
if($(':radio:checked').length > 0){
$(':radio:checked').each(function (i) {
selectedvalue = $(this).val();
});
}
console.log(selectedvalue);
Here what I found and it working well for me.
function test_company_grp() {
var radios = document.getElementsByName("company_grp");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select the company group does this client belong's to!");
}
}
I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/
Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)
Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}
<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}
The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.
I have some ASP code which presents any where from 1-any number of checkboxes (which are named the same) on the page. This validation does work however I think its a bit weak:
if (document.getElementById('selectedDocs').checked)
{
//this is here to handle the situation where there is only one checkbox being displayed
}
else
{
var checked = false;
var field = myForm.selectedDocs;
for(var j = 0; j < field.length; j++)
{
if(field[j].checked == true)
{
checked = true;
break;
}
}
if(!checked)
{
alert("You have not ticked any options. At least one must be selected to proceed!")
return false;
}
}
I was working with the code in the else block but this only works when there is more than one checkbox. It ignores the fact I have ticked the one single option when there is only one. So I placed the code inside the if section......Although it woks its a bit of a hack, can someone kindly improve it for me?
Thanking you...
Use:
var field = myForm.getElementsByName('selectedDocs');
This always returns a NodeList that you can iterate over.
If they are in a form and all have the same name, they can be accessed as a collection that is a property of the form. So given:
<form id="f0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
<input type="checkbox" name="cb0" ...>
...
</form>
All the following return a reference to the form:
var form = document.getElementById('f0');
var form = document.forms['f0'];
var form = document.forms[0]; // if first form in document
and and all the following return a collection of the checkboxes named "cb0":
var checkboxes = form.cb0
var checkboxes = form['cb0'];
var checkboxes = form.elements.['cb0'];
I have a use case where the the number of radio buttons can be 1 or more, what is the best practice to check
i.e
var radioElements = document.forms["formname"].elements["abc"];
for(var i=0; i < radioElements.length; i++) {
if(radioElements[i].checked) {
alert("blah..");
break;
}
}
This works when the DOM has
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
<input type=radio name=abc id=abc value=bbb/>
</form>
But fails to work when it has only one radio element
<form name="formname">
<input type=radio name=abc id=abc value=aaa/>
</form>
How can I make the above javascript work in both these cases.
You could use getElementsByName. This method always returns a collection which you can iterate over:
var radioElements = document.getElementsByName("abc");
for(var i=0; i < radioElements.length; i++)
{
if(radioElements[i].checked)
{
alert("blah..");
break;
}
}
See an example of this in action at jsfiddle.net/L6SKx/.
You're accessing the radio buttons wrong:
var radios = document.forms['formname'].abc;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert('#' + i + ' is checked, with value ' + radios[i].value);
}
}
As well, with your multiple radio button example, it's invalid to have the same ID on two or more separate DOM elements. An ID has to be unique on the page.