How do I find the previous checkbox to an element using jquery?
I'm writing a custom validation plug-in "cb-required" which acts like "required" if and only if the previous checkbox is checked. The idea is a checkbox followed by one or more dependent text fields and/or selects. I'm not concerned with hiding or disabling the dependent fields in anyway, I just want to enforce "required" if the checkbox is checked.
Right now I'm simply trying to get an alert to pop-up correctly and .prev() is not doing the trick:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).prev(":checkbox").attr("name"));
return true;
}, "This information is required");
The form fields look something like this:
<input name="EMVEnabled" type="checkbox" value="1" />EMV enabled<br />
<span style="font-size:0.8em">
<strong>EMV Template</strong>
<select name="EMVTemplate" size="1" class="cb-required">
<option></option>
<option value="1">Template 1</option>
<option value="2">Template 2</option>
</select><br />
</span>
<br />
<input name="CashAdvance" type="checkbox" value="1" />Cash advance<br />
<br />
<input name="ExpressPay" type="checkbox" value="1" />Express pay<br />
<span style="font-size:0.8em">
<strong>Floor Limit Min</strong>
<input name="ExpressPayFloorMin" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
<strong>Floor Limit Max</strong>
<input name="ExpressPayFloorMax" type="text" value="" size="12" maxlength="12" class="cb-required numeric" /><br />
</span>
Using your specific example, .prev(":checkbox") isn't working because that method does not move up the DOM treeāit will only look at direct siblings. You want to use .parent().prev(":checkbox") or parent.prevAll(":checkbox") if there is a chance that another DOM element would be between the checkbox and the dependent input's parent.
Alternatively, you may want to look into specifying, in your .validate({}) declaration for the "cb-required" rule, the exact checkbox (by jquery selector string) to use for validation, rather than relying on the structure of the DOM. This would give you the flexibility to place your checkbox anywhere in the DOM relative to the input(s) that depend on its checked state, like so:
$form.validate({
rules: {
ExpressPayFloorMin: {
"cb-required": "[name=ExpressPay]"
}
}
});
Using this method, you would need to add a third argument "param" to your validation function, which would be the selector specified in .validate():
$.validator.addMethod("cb-required", function(value, element, param) {
return $(param).prop("checked") && ($(element).val().length > 0);
}, "This information is required");
Believe it or not, your alternate method got me thinking of another way to tackle the problem. In the html I wrapped the checkbox and the dependencies in a div with class="cb-group" attribute. then the following tweak works:
$.validator.addMethod("cb-required", function(value, element) {
alert("current="+$(element).attr("name")+" / previous="+$(element).closest(".cb-group").find(":checkbox").attr("name"));
return true;
}, "This information is required");
Now I can continue and finish with the real logic. Thanks.
Related
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!
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/
I have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?
placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}
You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city
Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}
at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark
try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }
See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".
You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].value = "";
}
}
}
I have a dynamic form that adds users to the site, made so you can duplicate the fields to add several users on one go.
So, my looks like
<input name="user[1][name]" value="" />
<input name="user[1][username]" value="" />
<input name="user[1][password]" value="" />
And then the number is changed on the duplicated fields, eg:
<input name="user[2][name]" value="" />
<input name="user[2][username]" value="" />
<input name="user[2][password]" value="" />
and so on.
On PHP I can handle each user since it has it's own array.
But I would like to validate, for example, the username on each user via jQuery.
The closest I got to is
$(this).find('input[name="user[][username]"]').each(function() {
But for it to work I need to explicitly write the number on the first [], eg:
$(this).find('input[name="user[1][username]"]').each(function() {
Is there a way to select ALL of them? I tried putting * and * between the [] but it didn't work.
Thanks for your help!
You can use the ends with selector
You could use a for loop and not have to write the numbers yourself really easily:
var number_of_forms = 3
for(var i=1;i<=number_of_forms;i++){
$(this).find('input[name="user[' + i + '][username]"]').each(function() {
}
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.