JavaScript if check-box is checked not working - javascript

I have a website form where I have fields that I want to be required (with JQuery Plugin) only when the check-box is checked.
So far I wrote JavaScript that works if the the check-box is not checked, or checked. But when a user checks the check-box and then unchecks it the code does not work (field is still mandatory when unchecked).
Also one other bug is for some reason this same code only works for updating only one items required boolean. For example if I have the same code but make it so two elements requirements are updated the script does not work at all.
Here is the relevant source code:
<script>
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "true");
}else{
document.getElementById("element1").setAttribute("required", "false");
}
}
</script>
<form>
<input type="checkbox" onclick="swap();" id="must" name="must" value="1" style="width:10;">
<input id="element1" type="text" name="element1" placeholder="Enter Value" >
<input type="submit" id="submit" name="submit" value="Send" >
</form>
Any assistance would be greatly appreciated.

Best way I know to check if checkbox is checked, it to use jQuery is() method (documentation). It handles x-browser differences for you. Also best way to add attribute to HTML element is to use attr() method.
if($("#must").is(":checked")) {
$("#element1").attr('required', 'required');
} else {
$("#element1").removeAttr();
}
You can check in DOM inspector that attribute is added.
Required attribute documentation is here.

Try this, in xhtml we specify required="required" and there no required="false", a better way is to remove attribute required on else
<script type="text/javascript">
function swap(){
if(document.getElementById('must').checked){
document.getElementById("element1").setAttribute("required", "required");
}else{
document.getElementById("element1").removeAttribute("required");
}
}
</script>

The required attribute is a boolean attribute, it presence means that the field is required and its absence means the field isn't required. It has only 3 valid forms 1. required alone by itself 2. required="" equal to an empty string 3. required="required"

Related

How to Completely Prevent Web Form Input Text Item change

I have this simple web-form
<form id="MyFormDiv" method="post">
<input type="number" name="cmp_no" id="id_cmp_no">
<input type="text" name="cmp_lname" maxlength="40 id="id_cmp_lname">
<input type="submit" name="submit" value="Save" id="submit-id-submit">
</form>
and this form will be used for both add and update.
When insert I have no problem, but when update I don't want to allow user to update or change the value of item which its id= "id_cmp_no"
I used javascript code to set its readonly property to true but that was not the 100% solution, because user can use browser inspect tool and see page source and change it's value before submitting the form, and therefore the readonly property is not useful.
Can I override it's onchange event to prevent change of it's value even if the value changed from page source using inspect tool.
Any one can help, thank you in advance
There is nothing that stops a user from changing values in browser, u can try solutions given in the above answers but be cautious user can dig out number of ways to do so like by using firebug/inspect element/ what ever..
What we can do is checking our values on server side and prompting user if they mismatch.
Shouting again ..
Never trust/depend on client....
If a user is skilled enough to open dev tools and change values from there, chances are they can also alter any JS code that prevents editing the readonly value.
So, there is no substitute to proper server-side validation.
You could check that the value is not being altered from the form's onsubmit event handler (see below), but keeping in mind what I and many commenters stated above.
$("form").on("submit", function(e) {
//check value of the input
if(this.someInput.value != 1) {
//do something here
//return false; if you want to block submit
}
return true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="number" name="someInput" readonly value="1"/>
<button type="submit">Submit</button>
</form>

Click Checkbox to disabled button

I want to disabled the button to send the form until the checkbox is set and i want to solve it with a nice short jQuery Code. But there has to be a bug, nothing happens. Does anyone have an idea?
JS:
$(document).ready(function(){
$('#terms').keyup(function(){
if($('#terms').is(':checked')){
$('#btn').removeAttr('disabled');
}else{
$('#btn').attr('disabled');
}})}
HTML:
<input id="terms" type="checkbox" value="" name="terms">
<input id="btn" name="register" type="button" value="Register" disabled/>
Actually it's really simple:
$('#terms').on("change", function() {
$("#btn").prop("disabled", !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="terms" type="checkbox" value="" name="terms">
<input id="btn" name="register" type="button" value="Register" disabled/>
where the !this.checked is the boolean value of the current checkbox state.
Naturally there's a jQuery way: $(this).is(":not(:checked)") but there's no need to, since you should get used to understand the this environment and the DOM Properties you have available using simple vanilla JS read more.
Use prop() instead of attr:
e.g.
$('#btn').prop('disabled', true);
Properties generally affect the dynamic state of a DOM element without
changing the serialized HTML attribute. Examples include the value
property of input elements, the disabled property of inputs and
buttons, or the checked property of a checkbox. The .prop() method
should be used to set disabled and checked instead of the .attr()
method. The .val() method should be used for getting and setting
value.
Note: You are using keyup instead of the change event for a checkbox.
Note your example can be simplified to just pass a boolean expression for on/off:
$(function(){
$('#terms').change(function(){
$('#btn').prop('disabled', !$(this).is(':checked'));
});
});

How to set an HTML5 input to required via JavaScript

I have a form with many input fields and radio buttons.
Some fields must get the required - attribute. But which fields are required depends on which radio button has clicked.
(If "Company-email" is checked -> input field "Company email" is required, otherwise private email)
Initially all field should be required=false.
But that does not work. No matter which value I give to the required-attribute, required is always true.
So... how can I set an input-field initially to required=false?
EDIT:
Thank you all for your answers.
In fact nothing works.
I made a test html document like this:
function test2()
{
document.getElementById("33").attr("required");
}
<form method="post" action="#">
<input type="text" id="33">
<input type="text">
<input type="text">
<input type="text">
<input type="radio" onclick="test2()">
<input type="submit" value="send">
</form>
It's unbelievable but this very simple example does not work.
The field with id 33 is not a required-field.
I can submit the form and nothing is checked.
What is wrong here?
EDIT 2:
Now I found the solution:
function test2()
{
document.getElementById("33").required = true;
}
This works for me on my example page. I have to check if i really can work with that in my real project.
required is a boolean attribute, so no matter what value you give it will still be required.
Instead of setting attributes you can set the element property
document.getElementById('companyemail').required = false;
Remove the required attribute from the fields that are not required.
In HTML5, this is an example of how to use required:
<input type="text" name="name" required>
So chances are that even when setting it to false (or anything, in fact) would be considered true.
$(document).ready(function() {
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
$('#checkbox1').change(function() {
if($(this).is(":checked")) {
$("#companyemail").attr("required");
$("#privateemail").removeAttr("required");
}
else{
$("#privateemail").attr("required");
$("#companyemail").removeAttr("required");
}
});
});
I hope this may help, let me know your feedback...
try to remove the required attributes
your-input.removeAttr( "required" );

How to check inputs in <form> and send form correctly

I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.

jQuery Validation plug-in – turning off validation based on class attributes

How can I instruct jQuery Validation plug-in to turn off validation based on class attributes and just work based on json rules?
This is conflicting with my jQuery templating system.
First, in your JQuery ready function set the class to 'ignore' or 'require' for each element:
$("#name").attr("class", "required");
$("#email").attr("class", "ignore");
Second, set validate function to ignore the 'ignore' class:
$("#form1").validate({ignore: ".ignore"});
This will require the name but ignore the email.
Looking at the source of jquery.validate.js, there is a variable called classRuleSettings, which stores the validation types based on class names. Set it to a 0 length array and you shold be good.
Try this():
<form>
<input type="text" class="required"/>
<input type="Submit"/>
</form>
<script type="text/javascript">
$.validator.classRuleSettings = []; //I am not sure about any side effects because of this
$("form").validate();
</script>
You can use ignore option
$("form").validate({ignore:".ignore"});
<input type="text" id="fName" class="required ignore"/> <!--fname won't be "required"-->

Categories