Happy.js radio button validation - javascript

Here is my radio buttons list:
<ul>
<li>
<input id="radio_1" type="radio" name="radio-button" />
<label for="radio_1">Radio 1</label>
</li>
<li>
<input id="radio_2" type="radio" name="radio-button" />
<label for="radio_2">Radio 2</label>
</li>
</ul>
I'm validating these radio inputs via Happy.js (http://happyjs.com/). I'm trying to check if any radio is checked. If neither is checked, than show single error message.
The problem is that Happy.js generates error messages for every radio input.
Here is fiddle -- http://jsfiddle.net/HhZtF/

The problem is in your error function.
function getError(error) {
return $('<div id="' + error.id + '" class="hint error">' + error.message + '</div>');
}
You should update a 'status' div ID .
For example have a div where you want the error.
<div id="formError"></div>
This should be display:none; by default.
Then in your error function you will update this area.
function getError(error) {
$('#formError').append( '<span class="error">This is an error - something is missing</span>' );
$('#formError').show(); // This will display the error box.
}
Something like this will help. Of course you will need to do a bit more but you should get the idea.
Also this assumes you are using jQuery also, but you added it as one of your tags so i took the liberty of taking it for granted.

The happy.js provides the errorTarget method. You can use it to specify error location.
errorTarget (string): Selector to use in lieu of the input element itself when choosing where to insert the error html. Error html will be inserted .after() this selector
Final code
<ul id="single-error">
<li>
<input id="radio_1" type="radio" name="radio-button" />
<label for="radio_1">Radio 1</label>
</li>
<li>
<input id="radio_2" type="radio" name="radio-button" />
<label for="radio_2">Radio 2</label>
</li>
</ul>
And then in your js you will have
$('#form').isHappy({
fields: {
' input[name=radio-button]': {
required: 'sometimes',
message: 'Error',
test: function () {
return $('input[name=radio-button]').is(':checked');
},
errorTarget: '#single-error'
}
}
});

Related

Tick checkbox via javascript console by lable names

I would like to check boxes via javascript.
The thing is I have a task to check more then 300 checkboxes whith specific names.
I can check one box, or check all boxes... but how to check specific boxes?
Here is an example:
<li id="s1" class="city-select">
<input name="rid" id="r1" value="1" type="checkbox">
<label for="r1" id="l1">Paris</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r2" value="2" type="checkbox">
<label for="r2" id="l2">Plovdiv</label>
</li>
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
I would like to tick only "Berlin" and "Paris" - here is what I'm using to tick all:
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'),function(el){el.checked=true});
And here is what am I trying to type:
$("lable:contains('paris, berlin')").prev().find('input').addAttr("checked");
You have wrong selector to target checkboxes. You need to use:
$("label:contains(Paris),label:contains(Berlin)").prev().prop("checked",true);
Working Demo
Update:
var cities = ["Paris","Berlin"];
$("label:contains('" + cities.join("'),label:contains('") + "')").prev().prop("checked",true);
Working Fiddle for update
It looks like your use of prev should be parent or closest.
So you take the current label, go up to the container, then down to the checkbox.
If you use prev then you restrict how much you can change the html (eg if you add a div wrapper around the label in the future, you'll have to change all your code).
given:
<li id="s1" class="city-select">
<input name="rid" id="r3" value="3" type="checkbox">
<label for="r3" id="l3">Berlin</label>
</li>
then use
$("label:contains(Paris),label:contains(Berlin)")
.closest("li")
.find(":checkbox")
.prop("checked",true);
More info at the API documentation: https://api.jquery.com/closest/
How to use this for 300 cities?
This depends on how they are stored. If it's a comma separated list (Paris,Berlin) then split into an array first, if it's json, then convert to an array first...(see the pattern?)
var citiesList = "Paris,Berlin".split(",");
$(citiesList).each(function() {
$("label:contains(" + this + ")")
.closest("li")
.find(":checkbox")
.prop("checked",true);
});

Input field appear after selecting a check box. HTML

I have a Twitter Bootstrap form that has 6 vertical check boxes. I need to have an input form field each time they select a checkbox. It could be in the form of a popup or maybe something that appears out to the right of the checkbox. I figure this is some kind of javascript function but I have no idea how to do so. Any suggestions would be greatly appreciated. Each textbox if selected should have a field that pops up asking them for how many years experience they have in this certain field. This will info will be collected via $_POST variables. So each checkbox popup should have its own unique name so i can post it.
<div class="form-group">
<label class="col-md-4 control-label" for="positionsought">Position Sought</label>
<div class="col-md-4">
<div class="checkbox">
<label for="positionsought-0">
<input type="checkbox" name="positionsought" id="positionsought-0" value="Cutting">
Cutting
</label>
</div>
<div class="checkbox">
<label for="positionsought-1">
<input type="checkbox" name="positionsought" id="positionsought-1" value="Sewing">
Sewing
</label>
</div>
<div class="checkbox">
<label for="positionsought-2">
<input type="checkbox" name="positionsought" id="positionsought-2" value="Upholstery">
Upholstery
</label>
</div>
<div class="checkbox">
<label for="positionsought-3">
<input type="checkbox" name="positionsought" id="positionsought-3" value="Frame Department">
Frame Department
</label>
</div>
<div class="checkbox">
<label for="positionsought-4">
<input type="checkbox" name="positionsought" id="positionsought-4" value="Mill Room">
Mill Room
</label>
</div>
<div class="checkbox">
<label for="positionsought-5">
<input type="checkbox" name="positionsought" id="positionsought-5" value="Cushion">
Cushion
</label>
</div>
<div class="checkbox">
<label for="positionsought-6">
<input type="checkbox" name="positionsought" id="positionsought-6" value="Any">
Any
</label>
</div>
</div>
</div>
Although you already have found an answer, I believe that this would work better for your situation since you say you will have 6 checkboxes. This dynamically creates input fields for each checkbox by their names and removes them when the checkbox is unchecked.
First add this function to each checkbox onclick="dynInput(this);"
<input type="checkbox" name="check1" onclick="dynInput(this);" />
and add this to wherever you would like the inputs to display.
<p id="insertinputs"></p>
Then simply add this javascript function to your head.
<script type="text/javascript">
function dynInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
var div = document.createElement("div");
div.id = cbox.name;
div.innerHTML = "Text to display for " + cbox.name;
div.appendChild(input);
document.getElementById("insertinputs").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}
</script>
JsFiddle here: http://jsfiddle.net/brL6gy7r/
You can use JavaScript here to do the job. When the checkbox is clicked and checked (because you can also check out.) a dialog will pop-up with all input-fields you want. You can change the dialog part to your desires. but this part is your main function:
$(document).ready(function () {
$('#chkBox').click(function () {
if ($(this).is(':checked')) {
// create input field
} else {
// if checkbox is not checked.. dont show input field
}
});
});
For a full demo on how to do this with a dialog, click this link and observe
http://jsfiddle.net/Runman44/5vy1m233/
Notice that you will need jQuery (and jQuery UI if you want to use the dialog like me)
There is a zero-JavaScript version that is dead simple and works in all major browsers. It takes advantage of the :checked pseudo-class and the adjacency selector. It works with an arbitrary number of checkboxes.
HTML:
<input type="checkbox" />
<input type="text" />
CSS:
input[type=text] {
visibility:hidden;
}
input[type=checkbox]:checked + input[type=text] {
visibility:visible;
}
here is the live demo
If you prefer, you can use display:none and display:inline rather than the visibility property.
The example I've provided assumes that the text field immediately follows the checkbox in the markup, but some variant of sibling/child selectors can be used to select it no matter where it is, as long as it is either a sibling or child (direct or indirect) of the checkbox.

how to set radio checked of an input by .val()?

i want to select an input by his value.
the problem is that i got a 4 radio inputs
and when the user clicks "next" it saves the value of that answer in AnsW array.
and when the user clicks "back" i want the input radio button with the value that i have in my AnsW array to be checked, so the user can know what he has selected and change his answer to something else.
html code:
<ul>
<li class="li0">
<input type="radio" value="ch1" name="choice" id="li0"/>
<label for="li0"></label>
</li>
<li class="li1">
<input type="radio" value="ch2" name="choice" id="li1"/>
<label for="li1"></label>
</li>
<li class="li2">
<input type="radio" value="ch3" name="choice" id="li2"/>
<label for="li2"></label>
</li>
<li class="li3">
<input type="radio" value="ch4" name="choice" id="li3"/>
<label for="li3"></label>
</li>
</ul>
my code is:
function go_back(){
$("#back").bind("click",function(){
qNum--;
showQuestion(qNum);
if(AnsW.length === 0){
calcAnswers--;
}
alert(AnsW[qNum]);
tempAns = AnsW[qNum];//user last answer which is false i need this to make the radio button point to that answer
//alert( $("input[value='tempAns']"));
$("input").val(tempAns).attr('checked', true);
alert(tempAns);
//alert(tempAns);
AnsW.splice(-1,1);//delete the false answer from the array i need this to make sure that the answer is deleted and there wont be overload of wrong answers
//alert(deleteAns);
if(qNum === 0){
$("#back").css({"visibility":"hidden"})
}
});
}
jQuery selectors allow you to find elements based on their attributes, an exact match example:
$("element.class[attribute=value]")
Check the value attribute in the selector
$("input[value="+tempAns+"]").prop('checked', true)

Showing/hiding divs based on checkbox using jQuery

I have a form with a checkbox (contained within a label #contact). For the change action of this checkbox, I am showing/hiding a div (#options).
To ensure that if the checkbox is checked the #options div always is always shown (and avoid the situation where checking the checkbox actually hides the subjequent options), I am using this code:
$('#contact :checkbox').is(':checked') ? $("#options").show() : $("#options").hide();
This works fine. The problem I have is that instead of a single checkbox with an ID, I want to have multiple checkboxes. I want to show/hide the next instance of my .hidden class based on whether the previous checkbox (within a label with the class .trigger) is checked or not. I have tried this:
$(document).ready(function() {
if( $('.trigger :checkbox').is(':checked') ) {
$(this).parent().nextAll('ul.hidden').show();
} else {
$(this).parent().nextAll('ul.hidden').hide();
}
});
But to no avail. The checkboxes are in an unordered list, like this:
<ul>
<li><label class="trigger"><input type="checkbox" name="02" /> Trigger 1</label>
<ul class="hidden">
<li><label><input type="checkbox" name="02-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="02-sub2" /> Normal</label></li>
</ul>
</li>
<li><label><input type="checkbox" name="02" /> Normal</label></li>
<li><label><input type="checkbox" name="03" /> Normal</label></li>
<li><label class="trigger"><input type="checkbox" name="04" /> Trigger 2</label>
<ul class="hidden">
<li><label><input type="checkbox" name="04-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="04-sub2" /> Normal</label></li>
</ul>
</li>
</ul>
I can't see where I'm going wrong here; presumably my selector is incorrect, but I've played around with the syntax for ages and not got anywhere. Thanks in advance (and thank you for reading this far).
You need to run your code inside a change handler, so this refers to the checkbox you want, like this:
$(document).ready(function() {
$('.trigger :checkbox').change(function() {
if( $(this).is(':checked') ) {
$(this).parent().nextAll('ul.hidden').show();
} else {
$(this).parent().nextAll('ul.hidden').hide();
}
});
});
...and that can be made much shorter with .toggle(bool), like this:
$(function() {
$('.trigger :checkbox').change(function() {
$(this).parent().nextAll('ul.hidden').toggle(this.checked);
});
});
If you need it to run when the page loads, so the show/hide states match the checkbox, just call that change handler with .change() (shortcut for .trigger('change')), like this:
$(function() {
$('.trigger :checkbox').change(function() {
$(this).parent().nextAll('ul.hidden').toggle(this.checked);
}).change();
});
You know you can roll your own fields, right? The typical way to do that is with a "rel=" field that has no meaning in HTML but can be picked up and used in jquery.
if ($('#contact :checkbox').is(':checked')) {
$("#" + $('#contact :checkbox').attr('rel')).show();
} else {
$("#" + $('#contact :checkbox').attr('rel')).hide();
}
And then:
<li><label class="trigger"><input type="checkbox" name="04" rel="hidden-04" /> Trigger 2</label>
<ul class="hidden" id="hidden-04">
<li><label><input type="checkbox" name="04-sub1" /> Normal</label></li>
<li><label><input type="checkbox" name="04-sub2" /> Normal</label></li>
</ul>
</li>
So then, when the checkbox named 04 is checked, we look in its rel field for the id of the object to hide() or show(). I think that's a LOT easier than trying to walk the dom to find the target object.

jQuery Validation Plugin Multiple Checkboxes

I am having some difficulty in using the jQuery Validator plugin. I have a list of checkboxes with different name attributes and I can't seem to figure out how to ensure that at least one of them has been checked. Everything that I find on Google seems to only work when the name attribute is the same.
Here is some sample code (updated):
<ul id="email_lists">
<li>
<input name="checkbox1" type="checkbox" /> List 1
</li>
<li>
<input name="checkbox2" type="checkbox" /> List 2
</li>
<li>
<input name="checkbox3" type="checkbox" /> List 3
</li>
<li>
<input name="checkbox4" type="checkbox" /> List 4
</li>
</ul>
I want to make sure that at least one of those is checked. Unfortunately, I cannot make the names the same as it is form that submits to a third-party email marketing application and it is expecting specific name attributes for these checkboxes.
Update
I am aware of how to do this using plain jQuery, but I would prefer to use the jQuery Validator plugin since that is how all of the other validation on the page is done.
I can group those checkboxes using jQuery by saying $('#email_lists li');, but I'm not really sure how to use something like that and tell the jQuery Validator plugin to use that as a group.
Assuming that you can give the checkboxes a class name (the jQuery needs something to work with):
<input class="validationGroupOne" name="checkbox1" type="checkbox" />
<input class="validationGroupOne" name="checkbox2" type="checkbox" />
<input class="validationGroupOne" name="checkbox3" type="checkbox" />
<input class="validationGroupOne" name="checkbox4" type="checkbox" />
You should be able to plug in the .validationGroupOne class-selector in place of the, usual, name attribute.
This was my solution :-)
Use:
<div id="list">
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
<input name="chkbox" type="checkbox" />
</div>
<input type="hidden" name="the_real_field_name" />
Then in jquery validate plugin block:
rules : {
chkbox: "required"
},
Then store the values as an array into a single hidden field like:
function updateInput() {
var allVals = [];
$('#list :checked').each(function() {
allVals.push($(this).val());
});
$('#the_real_field_name').val(allVals);
}
$(function() {
$('#list input').click(updateInput);
updateInput();
});

Categories

Resources