Checkboxes with anchors - javascript

I have a ton of check-box's that are linked to anchors. When a check-box is clicked it goes to that anchor which is in the same page. Is there a better way to code this? I have about 50 check-box's so this function is packed with if statements.This is the working code for 2 of them:
<input type="checkbox" id="1" value="1" onclick="return send();"/>
<input type="checkbox" id="2" value="2" onclick="return send();"/>
<script>
function send(){
if(document.getElementById('1').checked){
window.location='#buy';
return false;
}
if(document.getElementById('2').checked){
window.location='#order';
return false;
}
//and this function goes on and on and on...
return true;
}
</script>
And then in the page where I want it to go has
<a name="buy"></a>
<a name="order"></a>

jQuery will save your nerves here:
$('input:checkbox').click(function () {
windows.location = $(this).attr('value');
});
Simply make sure you change the anchors to match the checkboxes.

If you added the hash into the value of the input like so:
<input type="checkbox" id="2" value="buy" onclick="return send(this);"/>
You could do it like so
<script>
function send(input)
{
if(input.checked)
{
window.location = input.value;
return true;
}
return true;
}
</script>
If that doesn't work you could also switch out the value to use ID or even a custom attribute. Whatever suits your fancy.

HTML:
<input type="checkbox" id="checkbox1" value="1" data-target="buy" onclick=" send(this)">
<input type="checkbox" id="checkbox2" value="2" data-target="order" onclick="send(this)">
Javscript:
function send(el){
var target = '#' + el.getAttribute('data-target');
window.location = target ;
}

Related

Change checkbox checked with JavaScript

I am trying to change a part of my html code with JavaScript, but I can't get it to work:
function trigger(){
document.getElementById('mycheckbox').innerHTML="<input type="checkbox" id="mycheckbox" checked>";
}
function triggerOff(){
document.getElementById('mycheckbox').innerHTML="<input type="checkbox" id="mycheckbox">";
}
<input type="checkbox" id="mycheckbox">
<button type="button" onclick="trigger()">test</button>
<button type="button" onclick="triggerOff()">test</button>
So if I press the button I want to add the checked status to my HTML and if I press the other button I want to remove the checked status.
Is this even possible?
All help is highly appreciated ! Thanks a lot guys!
You cannot set innerHTML to input type checkbox. Use the checked property to check/uncheck the checkbox
function trigger(){
document.getElementById('mycheckbox').checked = true;
}
function triggerOff(){
document.getElementById('mycheckbox').checked = false;
}
<input type="checkbox" id="mycheckbox">
<button type="button" onclick="trigger()">test</button>
<button type="button" onclick="triggerOff()">test</button>
Use checked property, like this:
function trigger(){
document.getElementById('mycheckbox').checked=true;
}
function triggerOff(){
document.getElementById('mycheckbox').checked=false;
}
<input type="checkbox" id="mycheckbox">
<button type="button" onclick="trigger()">test</button>
<button type="button" onclick="triggerOff()">test</button>
Just do it like that
function trigger(){
document.getElementById('mycheckbox').checked = true;
}
function triggerOff(){
document.getElementById('mycheckbox').checked = false;
}
The innerHTML property will create inside your mycheckbox another input element

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)
ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204
I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?
$jqLib("#ModellingTagID_*").change(function(){
var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
$jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
});
you can apply same class to all those checkboxes
<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
<li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>
and then you can make function for it's change event like this.
$(function(){
$('.yourcbclass').on('change', function() {
if($(this).is(':checked'))
{
//do your stuff here
}
});
});
see if this helps..
Very simple using this way:--
$("#envoyer").click(function(e) {
var myArray = [];
$(":checkbox:checked").each(function() {
myArray.push(this.value);
});
if(myArray == ''){
alert('Please check');
}else{
alert("Checked: " + myArray.join(","));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
one<input type="checkbox" name='checkbox0' value="one_name" checked>
two<input type="checkbox" name='checkbox1' value="one_name1">
three<input type="checkbox" name='checkbox2' value="one_name2">
<input type="button" id="envoyer" value="Envoyer Reponse" />
</body>
</html>
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.
cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.
$(document).ready(function(){
$('.someclass').on('change', function() {
alert($(this).attr("id"));
});
});

Can I pass a variable textarea id to a JavaScript function?

I've run into a follow-up problem with this excellent solution:
Select checkbox when clicking in textarea (JavaScript?).
I need to apply the solution to more than one textbox in the same form. Is it possible in any way to alter the code into something like this (not working):
<html>
<body>
<textarea id="iamtextarea" rows="4" cols="10" onfocus="onFocusTextArea('iamtextarea');" onblur="onBlurTextArea('iamtextarea');">Enter some text in textbox</textarea>
<input type="checkbox" name="iamcheckbox" id="iamcheckbox" checked="checked"> I am checkbox<br>
<input type="hidden" name="hiddenString" id="hiddenString" value="Enter some text in textbox">
</body>
</html>
<script type="text/javascript">
function onFocusTextArea(variableName) {
document.getElementById("iamcheckbox").checked = false;
}
function onBlurTextArea(variableName) {
if(document.getElementById(variableName).value==document.getElementById("hiddenString").value) {
document.getElementById("iamcheckbox").checked = true;
}
}
</script>
What I want to do is to pass a variable id of the textarea to the javascript function so that I can use the same function for more than one textarea. Is that possible?
See jsfiddle here. This takes an element and a checkboxid
function onFocusTextArea(checkboxId) {
document.getElementById(checkboxId).checked = false;
}
function onBlurTextArea(element, checkboxId) {
if (element.value === "") {
document.getElementById(checkboxId).checked = true;
}
}
Some sample HTML
<textarea id="iamtextareaone" onfocus="onFocusTextArea('checkboxone');" onblur="onBlurTextArea(this, 'checkboxone');"></textarea>
<textarea id="iamtextareatwo" onfocus="onFocusTextArea('checkboxtwo');" onblur="onBlurTextArea(this, 'checkboxtwo');"></textarea>
<input type="checkbox" id="checkboxone" checked="checked">Checkbox One<br>
<input type="checkbox" id="checkboxtwo" checked="checked">Checkbox Two<br>

jQuery checkbox validation without form

I want to make a validation function with jQuery or pure javascript.
this is my checkbox
<input type="checkbox" name="terms" id="terms">
and this is my link button
<label id="kosullar" for="terms">
<a class="fancybox-effects-d" data-fancybox-type="iframe" onclick="" href="kosullar.php">KULLANIM KOSULLARINI KABUL EDIYORUM</a>
</label>
If checkbox is checked process will continue to redirect my href url if not i want to show alert() to user.
Thats it.
Would you show me an example?
Can you try this,
function Accept(dat){
var terms = $('#terms').is(':checked');
if(terms){
window.location.href=dat.href;
}else{
alert('not checked!');
return false;
}
}
HTML Section:
<input type="checkbox" name="terms" id="terms">
<label id="kosullar" for="terms">
<a class="fancybox-effects-d" data-fancybox-type="iframe" onclick="return Accept(this);" href="kosullar.php">KULLANIM KOSULLARINI KABUL EDIYORUM</a>
</label>
Another method:
$(function(){
$(".fancybox-effects-d").click(function(){
var terms = $('#terms').is(':checked');
if(terms){
window.location.href=$(this).attr('href');
}else{
alert('not checked!');
return false;
}
});
});
HTML:
<input type="checkbox" name="terms" id="terms">
<label id="kosullar" for="terms">
<a class="fancybox-effects-d" data-fancybox-type="iframe" href="kosullar.php">KULLANIM KOSULLARINI KABUL EDIYORUM</a>
</label>
In your onclick define a function and pass this, return false to stop the default action
onclick="verifyCheck(this); return false;"
function verifyCheck(elem) {
var cb = document.getElememtById("terms");
if (cb.checked) {
location.href = elem.href;
} else {
alert("Check the box!");
}
}
$('.fancybox-effects-d').click(function(e) {
if (!($('#fancybox-effects-d').is(':checked'))) {
e.preventDefault();
}
});
Try this.
<a class="fancybox-effects-d" data-fancybox-type="iframe" onclick="return Validate();" href="kosullar.php">
Javascript method
function Validate()
{
If($("#terms").is(":checked"))
{
//do your code to go to next step
}
else
{
alert("Please check the checkbox");
return false;
}
}

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
$("form :radio")
How do I know which one is selected?
To get the value of the selected radioName item of a form with id myForm:
$('input[name=radioName]:checked', '#myForm').val()
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
Use this..
$("#myform input[type='radio']:checked").val();
If you already have a reference to a radio button group, for example:
var myRadio = $("input[name=myRadio]");
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(":checked").val();
Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();
This should work:
$("input[name='radioName']:checked").val()
Note the "" usaged around the input:checked and not '' like the Peter J's solution
You can use the :checked selector along with the radio selector.
$("form:radio:checked").val();
If you want just the boolean value, i.e. if it's checked or not try this:
$("#Myradio").is(":checked")
Get all radios:
var radios = jQuery("input[type='radio']");
Filter to get the one thats checked
radios.filter(":checked")
Another option is:
$('input[name=radioName]:checked').val()
$("input:radio:checked").val();
In my case I have two radio buttons in one form and I wanted to know the status of each button.
This below worked for me:
// get radio buttons value
console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="toggle-form">
<div id="radio">
<input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
</div>
</form>
Here's how I would write the form and handle the getting of the checked radio.
Using a form called myForm:
<form id='myForm'>
<input type='radio' name='radio1' class='radio1' value='val1' />
<input type='radio' name='radio1' class='radio1' value='val2' />
...
</form>
Get the value from the form:
$('#myForm .radio1:checked').val();
If you're not posting the form, I would simplify it further by using:
<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />
Then getting the checked value becomes:
$('.radio1:checked').val();
Having a class name on the input allows me to easily style the inputs...
try this one.
it worked for me
$('input[type="radio"][name="name"]:checked').val();
In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:
radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();
where selectOneRadio ID is radiobutton_id and form ID is form_id.
Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).
Also, check if the user does not select anything.
var radioanswer = 'none';
if ($('input[name=myRadio]:checked').val() != null) {
radioanswer = $('input[name=myRadio]:checked').val();
}
If you have Multiple radio buttons in single form then
var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();
var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();
This is working for me.
I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.
(function ($) {
function changeRadioButton(element, value) {
var name = $(element).attr("name");
$("[type=radio][name=" + name + "]:checked").removeAttr("checked");
$("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
$("[type=radio][name=" + name + "]:checked").change();
}
function getRadioButton(element) {
var name = $(element).attr("name");
return $("[type=radio][name=" + name + "]:checked").attr("value");
}
var originalVal = $.fn.val;
$.fn.val = function(value) {
//is it a radio button? treat it differently.
if($(this).is("[type=radio]")) {
if (typeof value != 'undefined') {
//setter
changeRadioButton(this, value);
return $(this);
} else {
//getter
return getRadioButton(this);
}
} else {
//it wasn't a radio button - let's call the default val function.
if (typeof value != 'undefined') {
return originalVal.call(this, value);
} else {
return originalVal.call(this);
}
}
};
})(jQuery);
Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.
You can visit this jsFiddle to try it in action, and see how it works.
Fiddle
$(".Stat").click(function () {
var rdbVal1 = $("input[name$=S]:checked").val();
}
This works fine
$('input[type="radio"][class="className"]:checked').val()
Working Demo
The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.
API for :checked Selector
To get the value of the selected radio that uses a class:
$('.class:checked').val()
I use this simple script
$('input[name="myRadio"]').on('change', function() {
var radioValue = $('input[name="myRadio"]:checked').val();
alert(radioValue);
});
Use this:
value = $('input[name=button-name]:checked').val();
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Sales Promotion</td>
<td><input type="radio" name="q12_3" value="1">1</td>
<td><input type="radio" name="q12_3" value="2">2</td>
<td><input type="radio" name="q12_3" value="3">3</td>
<td><input type="radio" name="q12_3" value="4">4</td>
<td><input type="radio" name="q12_3" value="5">5</td>
</tr>
</table>
<button id="submit">submit</button>
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata
It'll give you a js object of the answers, so a form like:
<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>
will give you:
$("form").formalizeData()
{
"favorite-color" : "blue"
}
JQuery to get all the radio buttons in the form and the checked value.
$.each($("input[type='radio']").filter(":checked"), function () {
console.log("Name:" + this.name);
console.log("Value:" + $(this).val());
});
To retrieve all radio buttons values in JavaScript array use following jQuery code :
var values = jQuery('input:checkbox:checked.group1').map(function () {
return this.value;
}).get();
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Another way to get it:
$("#myForm input[type=radio]").on("change",function(){
if(this.checked) {
alert(this.value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<span><input type="radio" name="q12_3" value="1">1</span><br>
<span><input type="radio" name="q12_3" value="2">2</span>
</form>
From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {
// this outright does not work properly as explained above
$('#reported label').click(function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="click event"]').html(query + ' at ' + time);
});
// this works, but fails to update when same label is clicked consecutively
$('#reported input[name="filter"]').on('change', function() {
var query = $('input[name="filter"]:checked').val();
var time = (new Date()).toString();
$('.query[data-method="change event"]').html(query + ' at ' + time);
});
// here is the solution I came up with
$('#reported label').click(function() {
var query = $('#' + $(this).attr('for')).val();
var time = (new Date()).toString();
$('.query[data-method="click event with this"]').html(query + ' at ' + time);
});
});
input[name="filter"] {
display: none;
}
#reported label {
background-color: #ccc;
padding: 5px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
}
.query {
padding: 5px;
margin: 5px;
}
.query:before {
content: "on " attr(data-method)": ";
}
[data-method="click event"] {
color: red;
}
[data-method="change event"] {
color: #cc0;
}
[data-method="click event with this"] {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
<input type="radio" name="filter" id="question" value="questions" checked="checked">
<label for="question">Questions</label>
<input type="radio" name="filter" id="answer" value="answers">
<label for="answer">Answers</label>
<input type="radio" name="filter" id="comment" value="comments">
<label for="comment">Comments</label>
<input type="radio" name="filter" id="user" value="users">
<label for="user">Users</label>
<input type="radio" name="filter" id="company" value="companies">
<label for="company">Companies</label>
<div class="query" data-method="click event"></div>
<div class="query" data-method="change event"></div>
<div class="query" data-method="click event with this"></div>
</form>
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
var radValue= "";
$(this).find('input[type=radio]:checked').each(function () {
radValue= $(this).val();
});
})
});

Categories

Resources