Validate form with checkboxes using Javascript - javascript

I have a set of checkboxes in a form as follows:
<form name="form1" onsubmit="return window.Validate()" method="post" action="myprog.cgi">
<div id="filters">
<input name="One_f" type="checkbox"> No. 1<br>
<input name="Two_f" type="checkbox"> No. 2<br>
<input name="Three_f" type="checkbox"> No. 3<br>
</div>
<div id="Colors">
<input name="Red" type="checkbox"> Red<br>
<input name="Blue" type="checkbox"> Blue<br>
<input name="Green" type="checkbox"> Green<br>
</div>
<div id="Button">
<input name="Submit" value="Submit" type="submit">
</div>
</form>
I want to write a function Validate in Javascript that would see whether any of the checkboxes in the div id
filters is checked. If none of them is checked, it should show an alert box and prevent the cgi from
getting executed. The checkboxes in the div filters all have their names ending in _f, if that helps.
How do I write such a function?

Here's a jQuery solution, I'll add a plain JS one in a few moments.
$('form[name="form1"]').on('submit', function(e) {
if(!$('#filters input:checkbox:checked').length) {
e.preventDefault();
alert('Please select at least one filter.');
}
});
This codes does not require the onsubmit inline event.
Since you are not familiar with jQuery I'll explain it more thoroughly:
$('form[name="form1"]') creates a jQuery object containing all elements matching the selector. It would be faster if you gave your form id="form1" and used $('#form1')
.on() binds an event handler. The first argument passed to the callback function is a wrapped event object which we'll need to prevent the form from being submitted if necessary.
$('#filters input:checkbox:checked') selects all checked checkboxes that are children of #filters. :checkbox and :checked are pseudo-selectors which will only match checkboxes that are currently checked)
.length is the number of elements in the jQuery object - if nothing is checked it's zero
e.preventDefault(); prevents the default action of the event from being executed, i.e. the form will not be submitted.
Usually you would wrap the whole code with $(document).ready(function() { ... }); to make it execute as soon as the DOM is ready - if you put the <script> tag containing the code after the </form> tag of your form, it's not necessary though.
If you really want a plain JS solution, try this:
function Validate() {
var container = document.getElementById('filters');
var checked = 0;
for(var i = 0; i < container.childNodes.length; i++) {
var elem = container.childNodes[i];
if(elem.tagName == 'INPUT' && elem.type == 'checkbox' && elem.checked) {
checked++;
}
};
if(checked) {
return true;
}
alert('Please select at least one filter.');
return false;
}

Related

How would I .click this button?

I'm trying to press this button, this is the information from the inspect
<form action="?p=casino" method="post">
<input type="hidden" name="game" value="6">
<input type="submit" value="Play" class="button">
</form>
In other button presses I could simply do
var missionButton = document.getElementById(CrimeID); //CrimeID is the ButtonID from the /crimes page/ variables at the top of this script.
missionButton.click();
CrimeID is "Form1" so I was able to just select form1 and .click but I'm not able to do that with this one because there isn't a form id or anything and it's specific to the value (I need it to be 6) that's shown in the snippit.
There are many ways to select the <input type="hidden" name="game" value="6"> tag in JavaScript (is that what you want, right?).
If you want to use vanilla (ie pure) JavaScript, without JQuery, you can do:
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
if(inputs[i].getAttribute('name') === 'game' && inputs[i].getAttribute('value') === '6') {
var buttonYouWant = inputs[i];
}
}
buttonYouWant.click();
However, I would advise you to use JQuery if you can, because the implementation is far easier. Please check https://jquery.com/ for more.

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Disabling a Form using Javascript under condition of "yes or no"

I have this form with Yes or No question in a radio button style to indicate whether such form has been filled out and submitted before. I want to disable this form using Javascript if the answer is "yes", per user's answer.
The "yes" would indicate that the form has already been submitted before and therefore re-filling out of the form is not allowed. This is to attempt to stop double or multiple submission.
Any advise will be greatly appreciated.
Dawn26
I might use an onchange function attached to the "Yes" radio button to either hide the form or remove it from the page altogether. Your markup might look similar to this:
<form id="formId">
<input type="radio" value="Yes" onchange="YourClass.disableForm()"/>
...
</form>
And the javascript:
var YourClass = function() {
return {
disableForm : function() {
document.getElementById("formId").setAttribute("style", "display: none;");
}
};
}();
You can create a function that disables all form controls other than the checkbox based on whether it's selected or not. This doesn't stop duplicate submission, so you will still need to handle that at the server. You can also hide the controls if you like, but just disabling them is probably sufficient.
You may also want to put up a message to explain why the form controls are disabled.
function checkDisabled(target) {
var form = target.form;
var elements = form.elements;
var disable = target.checked;
// Check every control in the form
for (var i=0, iLen=elements.length; i<iLen; i++) {
// Don't disable the checkbox
if (elements[i] != target) {
// Disable (or not) based on whether checkbox is checked
elements[i].disabled = disable;
}
}
}
Some test markup:
<label for="dateTime">Date and time<input id="dateTime" name="dateTime">
<br>
<span class="screenTip">YYYY-MM-DD hh:mm:ss</span>
</label>
<form>
Have you submitted this form before?
<input type="checkbox" name="hasBeenSubmitted" value="1" onclick="checkDisabled(this)">
<br>
Foo: <input type="text" name="foo">
<br>
Bar: <input type="text" name="bar">
<br>
<input type="submit">
</form>

Input field hidden dynamically can not be shown later

I have a form with a text input and a radio button pair used to select yes/no. For purposes of keeping this simple, the radio button click event checks the value and if yes, it shows the input text field. If no, it hides the input field. I also check the initial state on document ready and show/hide the input text field.
I find that clicking No results in the input hiding using a jQuery .hide() method. But when I select Yes the resulting .show() method call does not show the input. If I set the radio to Yes and then refresh the page then the input shows up just fine.
Firebug show no input tag. It's like clicking No radio deleted the input from the DOM.
Here's the JS code sample:
$(document).ready(function() {
if ($('#cost_sharing_yes').attr('checked') == 'checked') {
$('input#Institutional_CS_TP').show();
} else {
$('input#Institutional_CS_TP').hide();
}
$('#cost_sharing_yes').click(function() {
$('input[id="Institutional_CS_TP"]').show();
});
$('#cost_sharing_no').click(function() {
$('input#Institutional_CS_TP').fadeOut("fast");
});
}
You are missing ) for closing ready function:
$(document).ready(function() {
} // <--
For getting the checked property of the inputs perperly you should use prop method instead of attr.
$(document).ready(function() {
var isChecked = $('#cost_sharing_yes').prop('checked');
$('#Institutional_CS_TP').toggle(isChecked);
// ..
})
I figured out my problem. It was a self-inflicted coding problem.
To keep the example simple I had removed another function call in the mix that I didn't think had any bearing on the problem. I was wrong. In that function I had
$('td#Institutional_CS_TP).text('$0');
$('input[name="Institutional_CS_TP"]').val('0.00');
This resulted in only the td value showing, not the input inside that same td.
Both my td and the input tags inside the td had the same ID values...not a good idea.
html code
<div id="myRadioGroup">
Value Based<input type="radio" name="cars" value="2" />
Percent Based<input type="radio" name="cars" value="3" />
<br>
<div id="Cars2" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Value</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_value" />
</div>
<div id="Cars3" class="desc" style="display: none;">
<br>
<label for="txtPassportNumber">Commission Percent</label>
<input type="text" id="txtPassportNumber" class="form-control" name="commision_percent" />
</div>
</div>
Jquery code
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
function myFunction1() {
var y = document.getElementById("myInput1");
if (y.type === "password") {
y.type = "text";
} else {
y.type = "password";
}
}

Calling onclick on a radiobutton list using javascript

How do I call onclick on a radiobutton list using javascript?
How are you generating the radio button list? If you're just using HTML:
<input type="radio" onclick="alert('hello');"/>
If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one by one:
foreach(ListItem RadioButton in RadioButtons){
RadioButton.Attributes.Add("onclick", "alert('hello');");
}
More info: http://www.w3schools.com/jsref/event_onclick.asp
To trigger the onClick event on a radio button, invoke the click() method on its DOM element:
document.getElementById("radioButton").click()
using jQuery:
$("#radioButton").click()
AngularJs:
angular.element('#radioButton').trigger('click')
I agree with #annakata that this question needs some more clarification, but here is a very, very basic example of how to set up an onclick event handler for the radio buttons:
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.
The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.
This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.
I think all of the above might work. In case what you need is simple, I used:
function checkRadio(name) {
if (name == "one") {
console.log("Choice: ", name);
document.getElementById("one-variable-equations").checked = true;
document.getElementById("multiple-variable-equations").checked = false;
} else if (name == "multiple") {
console.log("Choice: ", name);
document.getElementById("multiple-variable-equations").checked = true;
document.getElementById("one-variable-equations").checked = false;
}
}
<div class="radio-buttons-choice" id="container-3-radio-buttons-choice">
<input type="radio" name="one" id="one-variable-equations" onclick="checkRadio(name)"><label>Only one</label><br>
<input type="radio" name="multiple" id="multiple-variable-equations" onclick="checkRadio(name)"><label>I have multiple</label>
</div>
Try the following solution
$(document).ready(function() {
$('.radio').click(function() {
document.getElementById('price').innerHTML = $(this).val();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="variant">
<label><input type="radio" name="toggle" class="radio" value="19,99€"><span>A</span></label>
<label><input type="radio" name="toggle" class="radio" value="<<<"><span>B</span></label>
<label><input type="radio" name="toggle" class="radio" value="xxx"><span>C</span></label>
<p id="price"></p>
</div>
The other answers did not work for me, so I checked Telerik's official documentation it says you need to find the button and call the click() function:
function KeyPressed(sender, eventArgs) {
var button = $find("<%= RadButton1.ClientID %>");
button.click();
}

Categories

Resources