Looping through fields to validate with jQuery - javascript

Is there a way to do this with jQuery?
Here is setup:
<input type='checkbox' class='sk1' /> <input type='text' class='skill1' />
<input type='checkbox' class='sk2' /> <input type='text' class='skill2' />
<input type='checkbox' class='sk3' /> <input type='text' class='skill3' />
<input type="button" onclick="validate();" />
Important: The input field to the right of checkbox is associated with checkbox.
When button is clicked, I want this check: Each checkbox that is checked, can not have an empty input field to the right of it. When it finds one, it will stop and throw an alert.
Looking around, I see I will need to probably uses regex and perhaps the jQuery.each.
Pseudo code:
for each checkbox class^=sk[number]
check if input[type=text] that has a class with skill[same number as above]
if empty, alert,
Otherwise, continue checking other boxes
(Sidenote: Writing that pseudo makes me wonder if there is a better naming convention I can use so that I don't have to extract specific numbers out of these.)
(another note: When an checkbox is NOT checked, the text field is disabled; I have this working)
Can someone give me some guidence on this?

Just loop the checkboxes and check the next text element:
$(":checkbox:checked").each(function() {
if (!$(this).next(":text").val().length) {
alert("You must put in text!");
return false; //bail out of the loop, return true to skip to the next iteration
}
});
Demo: http://jsfiddle.net/uvQ6C/

Related

django auto check if i save it to database

Here is my html:
<input type="checkbox" value="1" name="Visual" id="visual">
<input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis">
<input type="checkbox" value="1" name="Skin" id="Skin">
<script type="text/javascript">
$('#checkbox-value').text($('#checkbox1').val());
$("#checkbox1").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
$('#checkbox-value').text($('#checkbox1').val());
});
</script>
Here is my view:
Visual = request.POST['Visual']
Tuberculosis = request.POST['Tuberculosis']
Skin = request.POST['Skin']
V_insert_data = StudentUserMedicalRecord(
Visual=Visual,
Tuberculosis=Tuberculosis,
Skin=Skin
)
V_insert_data.save(
Why is it every time I save the data to my database, the Visual, Tuberculosis and Skin are automatically checked even though I didn't check it when I was saving it? Or I think my javascript is wrong?
You don't need $('#checkbox-value').text($('#checkbox1').val());, unless you have such element on the page
which you haven't shown us.
You can't define more than one element on the same page with the same id.
(Same goes for the name attribute).
Use different ids as shown in my code and match the chekboxes by class/name.
Don't put value="1" inside your checkboxes.
Put your jQuery code inside a $(function() { }); which is an alias for $( document ).ready().
More info here.
Don't use bare request.POST values, use the sanitized self.cleaned_data['var_name'] instead.
I don't think it's a good idea to have param names with capital letters (this is just a note, it will not impact the functionality). According
to Python's PEP 8, only classes should start with a capital letter.
Frontend:
<input type="checkbox" name="Visual" id="checkbox1" class="checkbox-js-trigger-class">
<input type="checkbox" name="Tuberculosis" id="checkbox2" class="checkbox-js-trigger-class">
<input type="checkbox" name="Skin" id="checkbox3" class="checkbox-js-trigger-class">
<script type="text/javascript">
$(function() {
$(".checkbox-js-trigger-class").on("change", function(){
var new_val = $(this).is(':checked') ? 1 : 0;
$(this).val(new_val);
});
});
</script>
Backend:
It's best to use Model Form:
class StudentUserMedicalRecordForm(ModelForm):
class Meta:
model = StudentUserMedicalRecord
fields = ['Visual', 'Tuberculosis', 'Skin']
Because you have default value given as "1" here
<input type="checkbox" value="1" name="Visual" id="visual">
And also there is no element with id = "checkbox1" or id = "checkbox-value" which are referenced in your script.
Checkbox inputs are actually a little strange and work differently than how you think they work.
You don't need jQuery to handle the case when a checkbox has been changed. The browser and HTML handle that for you. (Sort of like how you don't need to listen for keys being pressed while the user is focused on a input type="text" to make letters show up in the text box.)
Instead, what happens is if the user checks the checkbox, the input will have an attribute called checked. It can look something like this .
The checkbox input tag also has two other attributes name and value. These are what get sent to the server when the form is submitted. BUT it only sends the name and value pair for the checkboxes that are checked! For the checkboxes that are not checked, it sends nothing. So if every checkbox has a name and value you can think of it as a key-value pair. If the check box is checked, it will send key=value to the server. You are allowed to have more than one value for a single key if you designate the name as being the name of an array.
So imagine you have a form like this:
<input type="checkbox" name="disease[]" value="tuberculosis" checked>
<input type="checkbox" name="disease[]" value="chickenpox" checked>
<input type="checkbox" name="disease[]" value="smallpox">
<input type="checkbox" name="needs_medicine" value="true" checked>
<input type="checkbox" name="recovered" value="whatevervalue">
When that form is submitted, the server will receive something that looks like "disease=[tuberculosis,chickenpox]&needs_medicine=true"
Notice that smallpox and recovered are not mentioned because they are not checked. Also notice that it's not super important what you put as the value of a checkbox that is not a multiple choice checkbox (in this example, needs_medicine) because the value that gets sent to the server will always either be the value of the checkbox (in this case, the string "true").

JQuery: Getting a series of checkboxes to validate

I'm trying to get a group of checkboxes as part of an overall form I created in the admin area of WordPress to validate. Basically, custom fields. Here's what the code looks like:
<div><label><input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2</label></div>
<div><label><input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5</label></div>
<div><label><input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8</label></div>
and so on.....
So I have this in my JavaScript:
jQuery(document).ready(function($) {
$('[name="_ecp_custom_3"]').attr("required", true);
$('[name="_ecp_custom_5[]"]').prop("checked", true);
});
First line for a text field, works great. But the checked one underneath doesn't work at all. If I submit the form without checking a box, the form still publishes and when it comes back, all the fields are now checked even though I didn't check any of them.
Puzzled what to do in regards to that since there's going to be several rules in this validation function.
If you are using html:
An html element name and id cannot include special characters, such as [ ], and must begin with a letter (A-Z), (a-z).
Aside from that, your jQuery references an element with the name=_ecp_custom_5 and not name=_ecp_custom_5[]. Simply remove the [] in your names and your code will work.
Update
The $('[name=foo]').prop("checked", true) sets all checkboxes with name=foo to checked. I'm a bit confused about what you are asking at this point, since it seems like you are confused about why your form is submitting all checkbox inputs as checked?
You want to require that at least one checkbox is checked, right?
You can iterate all inputs with the name attribute value of "_ecp_custom_5[]" by using jQuery.each(). With that, you can create any flag variable that will be used on any condition.
Please refer to the snippet below if you can't visualize what I am trying to say.
If you want to require that at least one checkbox is checked, you can use this example as your basis
$(function() {
$('#btnValidate').click(function() {
var flag = false;
$.each($('[name="_ecp_custom_5[]"]'), function(index, value) {
var checkboxStatus = $(this).prop('checked');
if (checkboxStatus == true) {
flag = checkboxStatus;
}
});
if (flag == false) {
alert('No checkbox has been checked')
} else {
alert('Success!')
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2
</label>
</div>
<div>
<label>
<input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5
</label>
</div>
<div>
<label>
<input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8
</label>
</div>
<button id="btnValidate" style="margin-top: 20px;">Validate</button>
How I did it?
I iterated all inputs with the name attribute value of "_ecp_custom_5[]".
Then I created a boolean variable named "flag" (default value is false) that is being changed to true only if a checkbox from the iteration has the prop('checked') value of true. If no checkbox has been checked, then the "flag" variable's value will remain false which will then be checked by my condition.

javascript code for required checkbox

I have a website and I'm trying to make my (extra cost) checkboxes required before proceeding to checkout with paypal. The checkboxes, when clicked, add extra money to the total price as well (not sure if that affects anything). I also cannot find the name= field for the checkboxes so I used id= which I'm sure is completely wrong. Sorry I am extremely new with this.
ALSO NOTE - after my checkbox form I have to go through 2 more pages of clicking a book now button before I arrive at the SUBMIT checkout button... not sure if this stops anything from working correctly? –
I have added the following to my custom css:
<form action="../" onsubmit="if (this.package-44.checked == false) { alert ('You didn\'t choose any of the checkboxes!'); return false; } else { return true; }">
<p><input type="checkbox" id="package-44" value="add" required="required" /></p>
<p><input type="submit" name="woocommerce_checkout_place_order" value="Proceed to PayPal" required="required" /></p>
</form>
I posted this in footer.php of my theme:
$('#formTemplate').submit(function() {
if (!attributeSupported("required") || ($.browser.safari)) {
//If required attribute is not supported or browser is Safari (Safari thinks that it has this attribute, but it does not work), then check all fields that has required attribute
$("#formTemplate [required]").each(function(index) {
if (!$(this).val()) {
//If at least one required value is empty, then ask to fill all required fields.
alert("Please fill all required fields.");
return false;
}
});
}
return false; //This is a test form and I'm not going to submit it
});
I have also changed the inputs to <required="required" />on the backend of my checkbox input. This is still not stopping me from proceeding with my checkout.
any more help is appreciated.
if I understand you that the checkbox is required. Is it?
Just change the checkbox line:
<p><input type="checkbox" id="package-44" value="add" required ></p>
There is a simple html code for required for html inputs.
add required="required" to the input element. Example:
<input type="checkbox" required="required" />
When you submit the form, and the checkbox isn't checked, the browser will give you an alert to inform you that you need to check the checkbox element.
And because you want to do this in javascript, you can take a look at this answer: How to set HTML5 required attribute in Javascript?
EDIT: See comment from Marko below about checking the submitted forms with the required tags.

Copy input field's value to multiple hidden fields... but with same ID's?

1) I have 3 input radio buttons with unique values.
For e.g.
<input type="radio" id="id1" value="This is first value" />
<input type="radio" id="id2" value="This is second value" />
<input type="radio" id="id3" value="This is third value" />
2) Next, I have 2 hidden form like this:
<form action="//mysite.com/process1.php"><input type="hidden" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" id="uniqueid" value=""></form>
3) Based upon whichever radio button the user clicks, I need to copy its value to the value of both the above forms hidden field.
For e.g. If user clicks on radio with id1, then it's value "This is first value" should be copied to both the forms hidden field.
CONSTRAINTS:
1) Have to use javascript or jquery, no server side processing available.
2) Note: both the final forms have one input field, but with same id. This is a constraint.
3) Why? Because based on some other actions on the page, the user gets to see one of the 2 forms. The only difference between them is their action is unique. All fields are same.
WHAT I HAVE SO FAR:
Using this, I am able to copy the value from the radio button to a hidden field's value, but it only copies to a field with a UNIQUE ID.
var $unique = $("#unique");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
Can someone guide as to how can the value be copied to multiple input fields, but with same id's?(Yes, the id's of the initial radio buttons can be unique.)
Having two HTML elements with same ID is an error.
You cannot treat this as a constraint, this is NOT a valid HTML code and it will cause inconsistent behavior in different browsers.
Use classes instead:
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" value=""></form>
And javascript:
var $unique = $(".uniqueid");
However, I couldn't find any #radio1 or #email in your code, are you sure you have the right selectors?
My recommendation for the JS will be: (Working jsFiddle)
var $unique = $(".uniqueid");
$('input[type="radio"]').click(function(){
$unique.val(this.value);
});
Notes for jsFiddle:
I've used click event instead of keyup (don't really understand why you used keyup here..).
I've given all radio buttons the same name so they will cancel each other out when selected.
I've turned the hidden fields to text so you could see the result.
<form action="//mysite.com/process1.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input type="hidden" class="uniqueid" id="uniqueid" value=""></form>
var $unique = $("input[type=hidden].uniqueid");
$("#radio1").keyup(function() {
$unique.val(this.value);
});
$("#email").blur(function() {
$unique.val(this.value);
});
As said by others, id must be unique. Try using a data-attribute:
<form action="//mysite.com/process1.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
<form action="//mysite.php/process2.php">
<input type="hidden" data-shouldupdate="true" value="">
</form>
Now you can use that attribute as selector to do something like:
$('[data-shouldupdate]').val(this.value);
I agree with all other who posted that id have to be unique to have correct HTML document. So if it's possible I strictly recommend you to fix the HTML document to remove all duplicates.
I write my answer only for the case that you can't remove id duplicates because of some reason and you still have the same requirements. In the case you should change the line
var $unique = $("#uniqueid");
to
var $unique = $("*[id=uniqueid]");
The selector *[id=uniqueid] (or just [id=uniqueid]) works slowly as #uniqueid, but it allows you to get all elements with the specified id attribute value. So it works even in case of id duplicates on the HTML page.
The most simple solution is to give a same name to both inputs. Check this link jsfiddle to see a working example. The code used is the one given is below:
HTML:
<input type="radio" name="copiedValue" id="id1" value="This is first value" />
<input type="radio" name="copiedValue" id="id2" value="This is second value" />
<input type="radio" name="copiedValue" id="id3" value="This is third value" />
<form action="//mysite.com/process1.php"><input name="uniqueid" id="uniqueid" value=""></form>
<form action="//mysite.php/process2.php"><input name="uniqueid" id="uniqueid" value=""></form>
jQuery/javascript:
$("input:radio[name=copiedValue]").click(function() {
$("input[name=uniqueid]").val($(this).val());
});
The radio-buttons should have the same name. I removed the type="hidden" so u can see it working correctly.
Hope it useful!

How to get value of textboxes, textareas, and radios in the same way in Javascript?

I want a function/code which will return the value that the user submitted for the field whose name/id is passed on to it. It shouldn't matter whether the field is a textbox, textarea, radio, or select. For example, the field could be:
<input type='radio' name='a_21' value='test' id='a_21_0' />
<input type='radio' name='a_21' value='test2' id='a_21_1' />
Or
<textarea name="a_21" rows="30" cols="6"></textarea>
When I do the call:
function getVal('a_21');
It should return the selected value.
How can I do this? Will:
document.myForm.field.value
work for textareas, dropdowns and radios, too?
The problem is different widgets have different purposes. For example, a <select> box with multiple selection available, multiple checkboxes, or even single checkboxes (whose value would be just "on" or "off") wouldn't have a single value, so it's ok for them to behave differently from other widgets.
But if you want to have a single function, you could do something like:
function getVal(obj){
if(obj.value){
return obj.value;
}
if(obj.selectedIndex){
return obj.options[obj.selectedIndex];
}
if(obj.checked){
return obj.checked;
}
return null;
}
Using jQuery you can do:
$('[name="a_21"]').val();
This will give you the value on of the field with name a_21, so matter what the type of field.
Note: The quotes are not needed, but I've gotten in the the practice of adding them because of checkbox arrays:
<input type="checkbox" name="ids[]" value="1" />
<input type="checkbox" name="ids[]" value="2" />
I figure it's better to be safe than trying to figure out why it doesn't work.

Categories

Resources