jquery- open and check radio button onclick - javascript

I have some radio buttons to filter data on my webpage that are working absolutely fine for me but i am failed to perform check on that radio button...
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label><br><br>
<input id="radio2" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=ceo'>
<label for="radio2">ceo</label><br><br>
<input id="radio3" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=company-head'>
<label for="radio3">company head</label>
I use jquery to open and perform check on radio button click.
jquery:
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location=$(this).attr('data-href');
});
// parse the url:
var scat = window.location.search.match(/scat=(\w+)/)[1];
if (typeof scat !== 'undefined') {
// update the correct radio button:
$('input[value="' + scat + '"]').prop("checked", true);
}
});
On using above query if i click on "ceo" radio button, It works for me absolutely fine i.e. it filters content for me and performs check also...
on the other hand if i click on bank manager or company head. It only filters content ..it dosen't perform check...Any help ??
Thanks in advance...
Note: data-href includes url having "-" in bank manager and company head and in label field both bank manager and company head are without "-".

You can put the & (You have incorrect notation used in URL i.e. &&) value as an data attribute as follows,
You have currently as ,
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label><br><br>
Add data-scat attribute to fetch scat value and also to be able to get clicked based on value,
<input id="radio1" type="radio" name="scat" value="bank-manager" data-scat="bank-manager" data-href='vlist.php?cat=xyz'>
<label for="radio1">bank manager</label><br><br>
And in jQuery you should access it as follows and append in your URL,
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location=$(this).data('href')+"&scat="+$(this).data('scat');
});
// parse the url:
var hrefLink = window.location.search;
// update the correct radio button:
$('input[value=' + hrefLink.substring(hrefLink.indexOf("scat")+5) + ']').prop("checked", true);
// } Commenting an extra closed bracket
});

Your regex need to be modified to fetch -, also need to change the selector to attribute ends with selector
var search = "?cat=xyz&scat=bank-manager"; //replace with window.location.search
var scat = search.match(/scat=([\w-]+)/);
if (scat && scat[1]) {
// update the correct radio button:
$('input[data-href$=' + scat[1] + ']').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=bank-manager'>
<label for="radio1">bank manager</label>
<br>
<br>
<input id="radio2" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=ceo'>
<label for="radio2">ceo</label>
<br>
<br>
<input id="radio3" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&scat=company-head'>
<label for="radio3">company head</label>

You have not specify the correct value to your radio input tags and you are using value in jQuery selector.Just add the right value to it and it will work fine.
It should be
<input id="radio1" type="radio" name="scat" value="bank-manager" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
insted of
<input id="radio1" type="radio" name="scat" value="1" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
$(document).ready(function() {
$('input[type=radio]').click(function() {
window.location = $(this).attr('data-href');
});
// parse the url:
var search = "vlist.php?cat=xyz&subcat=company-head";
// uncomment this line and comment below one
// var scat = window.location.search.match(/bcat=([\w-]+)/)[1];
var scat = search.match(/bcat=([\w-]+)/)[1];
if (typeof scat !== 'undefined') {
// update the correct radio button:
$('input[value="' + scat + '"]').prop("checked", true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="radio1" type="radio" name="scat" value="bank-manager" data-href='vlist.php?cat=xyz&&subcat=bank-manager'>
<label for="radio1">bank manager</label>
<br>
<br>
<input id="radio2" type="radio" name="scat" value="ceo" data-href='vlist.php?cat=xyz&&subcat=ceo'>
<label for="radio2">ceo</label>
<br>
<br>
<input id="radio3" type="radio" name="scat" value="company-head" data-href='vlist.php?cat=xyz&&subcat=company-head'>
<label for="radio3">company head</label>

Related

Radio button value selector

I am trying to write a form. In the form there will be one set of radio buttons. When I open my html page on my browser, I would like to click one of the buttons and then write its value in a text after I click a submit button.
This is part of the form code:
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
And this is part of my javascript code:
function buildData(){
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
return txtData;
}
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
});
But it is currently not working properly (it won't save the right selection in txt).
How can I fix it? Thanks in advance
UPDATE:
From one of the answers:
function buildData(){
var txtData =
"some text... " + $("[name=tipoBooster]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
}) + "other text...";
return txtData;
}
Here is a simple solution for getting user input when the user changes the checked radio button
$("[name=tb]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
but in your case you need to edit the build function to be like this
function buildData(){
return "type = " + ["custom","block","dark","f1b"][$("[name='tb']:checked").val()];
}
Or if you want more flexible solution you can add labels to your inputs
like this
$("[name='tb']").change(function() {
console.log($(this).parent().text().trim());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<label><input type="radio" name="tb" value="1" checked="checked" />block</label>
<label><input type="radio" name="tb" value="2" />dark</label>
<label><input type="radio" name="tb" value="3" />f1b</label>
<label><input type="radio" name="tb" value="0" />custom</label>
</dd>
<p></p>
</dl>
</form>
this was for a change event but your build function should be like this then
function buildData() {
return $("[name='tb']:checked").parent().text().trim();
}
Explanation:
$("[name='tb']:checked") gets the checked radio input element
.parent() gets its parent since we need the label to get its text
.text() gets the text of the label
.trim() removes white space before and after the text
Your selector is referencing an id not the name attribute. Try this instead.
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
You could use: $("[name='tb']").val() and just set the corresponding values on the actual radio buttons to block dark etc.
e.g:
<input type="radio" checked="checked" name="tb" value="block"/>
block
<input type="radio" name="tb" value="dark" />
dark
<input type="radio" name="tb" value="f1b" />
f1b
<input type="radio" name="tb" value="custom" />
custom
A # in a jQuery selector is for selecting by id attribute.
What if you change the selector from ($("#tb").is(":checked")... to a name selector.
e.g.
($("input[name*='tb']").is(":checked")
If you just want to get the selected radio button's text. Could you update the html to be.
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<input id="option1" type="radio" checked="checked" name="tb" value="1"/>
<label for="option1">block</label>
...
<p></p>
</dl>
</form>
Then your function can just return the selected text
function buildData(){
return "type = " + $("input[name*='tb']").is(":checked").next("label").text();
}
If you don't want to add labels to the html, then I would try $("input[name*='tb']").is(":checked").next().text();
Maybe sharing a minimum working example link would help, as I am just writing the above from memmory, referencing the documentation (https://api.jquery.com/text/#text).

How to add class based on input attribute in jquery?

I have some radio buttons that are not initially setting css where checked = "checked".
Any suggestions what type of jquery statement I could use to apply a class on to checked input radio buttons?
I have also attached my jsfiddle
https://jsfiddle.net/2Lbbf1b4/1/
$(function() {
$('label.radio-inline input').on('change', function() {
var name = $(this).attr('name');
if (true === $(this).prop('checked')) {
$('[name=' + $(this).attr('name') + ']').parent().removeClass('radio-select');
$(this).parent().addClass('radio-select');
}
});
});
<label class="radio-inline radio-style">
<input type="radio" checked="checked" name="test1" value="1" class="radio-style">
</label>
<label class="radio-inline radio-style">
<input type="radio" name="test1" value="2">
</label>
<br>
<label class="radio-inline radio-style">
<input type="radio" checked="checked" name="test" value="1" class="radio-style">
</label>
<label class="radio-inline radio-style">
<input type="radio" name="test" value="2">
</label>
You could simplify this a bit and and use jQuery's .is() helper method to check for the checked state of the input and compare it against it's siblings with a same name:
$(function() {
$('label.radio-inline input').on('change', function() {
if ($(this).is(':checked')) {
$('input[name="' + $(this).prop('name') +'"]').not($(this)).parent().removeClass('radio-select');
$(this).parent().addClass('radio-select');
}
});
});
Updated jsFiddle
You need to set the class on initialization using:
$('label.radio-inline input[type=radio]:checked').parent().addClass('radio-select');
Check the fiddle: https://jsfiddle.net/2Lbbf1b4/4/

on Focus not working when textbox selected

I have a form here which id like the users to be able to select the radio button to choose a pre-defined amount option, or press the textbox (focus) to select the custom amount. The purpose of the javascript below is to clear the textbox when a predefined amount has been selected. It also allows users to CLICK the textbox (onfocus) to enter a custom amount in the CP_otheramount field (also use the radio button as a fallback).
It all seems to be working except for the onfocus. It works perfectly on load...but try this scenario:
Load the page, click inside the textbox but then decide to change your mind by selecting the value 3 radio button (64)...and then decide to press inside the onfocus textbox amount again... it become disabled and stops you from clicking inside or writing a number in!
Can anyone see the problem here at all? Its strange because it works on Stackoverflow just not on the live site. ANy help would be really appreciated.
Here is what has been created so far:
function activate() {
$('#other').prop('checked', true);
$('#other').trigger('click');
$('#theamount').focus();
}
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('input[name="CP_otheramount"]').val('');
$('#theamount').removeAttr("disabled");
} else {
$('#theamount').prop("disabled", "disabled");
$('input[name="CP_otheramount"]').val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="am_payment" value="3" checked="checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11" checked="checked"> <strong>100</strong>
<input type="radio" name="am_payment" value="32" checked="checked"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span onclick="activate();"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
The problem with your code is that you are checking every radio button without un-checking them.
function activate() {
// $('#other').prop('checked', true); Remove this line;
$('#other').trigger('click');
$('#theamount').focus();
}
$('input[name="am_payment"]').on('click', function() {
if ($(this).val() === '') {
$('input[name="CP_otheramount"]').val('');
$('#theamount').removeAttr("disabled");
} else {
$('#theamount').prop("disabled", "disabled");
$('input[name="CP_otheramount"]').val('');
}
});
And also
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Only check one, or none by Default -->
<input type="radio" name="am_payment" value="3" checked = "checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11"> <strong>100</strong>
<input type="radio" name="am_payment" value="32"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span onclick="activate();"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
UPDATE:
It was working for me but I don't know why it's not working for you, so I rewrote the functions..See if this works for you.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="am_payment" value="3" checked = "checked"> <strong>64</strong>
<input type="radio" name="am_payment" value="11"> <strong>100</strong>
<input type="radio" name="am_payment" value="32"> <strong>250</strong>
<input type="radio" value="" name="am_payment" id="other">
<label>Other</label>
<span id="toggle"><input type="text" name="CP_otheramount" value="" id="theamount" disabled="disabled"/></span>
<script>
function activate(){
$('#theamount').attr('disabled',false);
$('#theamount').focus();
$('#other').click();
}
function deactivate(){
$('#theamount').val('');
$('#theamount').attr('disabled',true);
}
$('#toggle').click(function(){
activate();
});
$('input[name="am_payment"]').change(function(){
if($(this).val() != ""){
deactivate();
}else{
activate();
}
});
</script>

How to change input type dynamically using jquery or javascript

Below is the my html code:
<input type="checkbox" id="multiOptions" />IsForMultioptions
<input type="radio" value="1" name="option">option1
<input type="radio" value="2" name="option">option2
If I select checkbox i.e. multiOptions then all radio buttons should be convert into checkboxes.
and If I uncheck the checkbox i.e. multiOptions then all checkboxes should convert in radio buttons.
thanks in advance.
You'll need to actually remove and recreate the elements, because IE doesn't let you change the type of an input after it's created.
jQuery makes this fairly easy with replaceWith:
$("selector for the input to change").replaceWith('<input type="checkbox">');
So for instance:
$('input[type="radio"][name="option"]').each(function() {
$(this).replaceWith('<input type="checkbox" name="option" value="' + this.value + '">');
});
Or if the values may contain characters requiring entities:
$('input[type="radio"][name="option"]').each(function() {
var rep = $('<input type="checkbox" name="option">');
rep.attr("value", this.value);
$(this).replaceWith(rep);
});
Instead of replacing the elements you can have two groups of which one is hidden depending on the checkbox:
HTML
<input type="checkbox" id="multiOptions">IsForMultioptions</input>
<div id="radios">
<input type="radio" value="1" name="option">option1</input>
<input type="radio" value="2" name="option">option2</input>
</div>
<div id="checkboxes">
<input type="checkbox" value="1" name="option">option1</input>
<input type="checkbox" value="2" name="option">option2</input>
</div>
jQuery
$(document).ready(function() {
$('#checkboxes').hide();
$('#multiOptions').on('click', function() {
if ($(this).is(':checked')) {
$('#radios').hide();
$('#checkboxes').show();
}
else {
$('#radios').show();
$('#checkboxes').hide();
}
});
});
jsFiddle example.

I have multiple checkboxes, and want to make a rule for 2 of them so that if I select 1 the other cannot be selected

​<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Those are the checkboxes , I have tried to search all over the internet and didn't find anything.
I want to allow the user to check id 3 and 4 BUT if he checks 1 , then 2 is not available to check, or if he checks 2 then 1 is not available to check.
And to the unavailable to add a class .. named ..
grade-out{ color: #DDD;}
Hope u understand the problem. Thanks in Advance !!
I would add data-groupid attribute to your checkboxes to identify which group they belong to. And then add a click handler to checkboxes belonging to group, which would disable all other checkboxes in the same group when checked and enable them when unchecked..
Assumming your markup is consistent and labels are always predecessors of respective checkboxes, you can easily target them using the prev() method.
$('input:checkbox[data-group]').click(function() {
var groupid = $(this).data('group');
var checked = $(this).is(':checked');
if(checked) {
$('input:checkbox[data-group=' + groupid + ']').not($(this))
.attr('disabled', 'disabled')
.prev().addClass('grade-out');
} else {
$('input:checkbox[data-group=' + groupid + ']')
.removeAttr('disabled')
.prev().removeClass('grade-out');
}
});
DEMO
I would assign an attribute data-disable to disable certain elements and check onchange.
This is how I would do it:
<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1" data-disable="2,3"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2" data-disable="1"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​
and script:
$('input:checkbox​​​​​​​​​​​​​​​​​​')​.on('change', function(){
var toUncheck = $(this).attr('data-disable');
var self = $(this);
$.each(toUncheck.split(','), function(el, val){
if(self.attr('checked') == 'checked'){
$('#'+val).attr('disabled', 'disabled');
} else {
$('#'+val).removeAttr('disabled');
}
});
});​
JSFiddle Demo
You could use radio form inputs. Anyway, if it's a must to use checkboxes then you could use some javascript (with jQuery, for example)
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('checked',false);
});
It this what you're looking for?
Re-worked example: demo fiddle
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('disabled',true);
else theOtherOne.attr('disabled',false);
});
Although there are more complex and flexible solutions above if you wish a solid but clear usage sample look at this. Using id's make things easier.
http://jsfiddle.net/erdincgc/uMhbs/1/
HTML (added class and id) ;
<form>
<label for="1">Text 1</label>
<input class="checks" type="checkbox" id="option1" name="option1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input class="checks" type="checkbox" id="option2" name="option2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input class="checks" type="checkbox" id="option3" name="option3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input class="checks" type="checkbox" id="option4" name="option4" value="something4" id="4">
</form>
And JS
$('.checks').click(function(){
op1 = $('#option1') ;
op2 = $('#option2') ;
this_id = $(this).attr("id") ;
this_state = $(this).attr("checked");
if(this_id =="option1"){
if( this_state == "checked" ){
op2.attr("disabled",true);
}
else {
op2.attr("disabled",false);
}
op2.prev().toggleClass('disabled');
}
if(this_id=="option2"){
if( this_state=="checked" )
op1.attr("disabled",true);
else {
op1.attr("disabled",false);
}
op1.prev().toggleClass('disabled');
}
});
Use $("#element_id").hide(); for disabling the check box
Use $("#element_id").attr("checked", true); to check if the check box is selected
Use $("#element_id").addclass(); to add class to an element so in short search for jQuery selectors and you will find the solutions
Vist for more information http://api.jquery.com/category/selectors/ I hope I help take care

Categories