How to find specific ID with Jquery and perform action - javascript

I have 2 styles radio buttons with Enable / Disable, please check below..
<p class="switch-options">
<label class="cb-enable selected" data-id="company_slogan_check">
<span>Enable</span>
</label>
<label class="cb-disable" data-id="company_slogan_check">
<span>Disable</span>
</label>
<input id="company_slogan_check" class="checkbox" type="hidden" value="0" name="company_slogan_check">
<input id="company_slogan_check" class="checkbox main_checkbox" type="checkbox" value="1" name="company_slogan_check" checked="checked">
</p>
and I want to check if the "Enable" button is clicked I want to hide some DIV within the code. I am trying with the following code but nothing works..
jQuery('#company_slogan_check').click(function() {
alert('sssss');
});
it doesnt even respond to the click.. can someone please help..

data-id is not the same as an id, to which the css selector #something would apply to id="something".
It would be easier to use .switch-options input

thanks guys, I did another workaround.. cheers
if($(this).attr('data-id') == "company_slogan_check")
alert('clicked');

first of all ID's need to be unique as already mentioned..
second your not using radio buttons u use a checkbox..
and way not try the ":checked" ?
something like this:
$("#company_slogan_check").change(function(){
if($(this).is(':checked')){
// your function
}
});
hope this was helpful

Related

jQuery else clause not working [duplicate]

I have 3 radio buttons in my web page, like below:
<label for="theme-grey">
<input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
<input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
<input type="radio" id="theme-green" name="theme" value="green" />Green</label>
In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?
$("<radiobutton name attribute>").click(function(){});
Please tell me how to solve this problem.
This should do it, all of this is in the documentation, which has a very similar example to this:
$("input[type='radio'][name='theme']").click(function() {
var value = $(this).val();
});
I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.
To determine which radio button is checked, try this:
$('input:radio[name=theme]').click(function() {
var val = $('input:radio[name=theme]:checked').val();
});
The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.
Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.
$('input:radio[name=theme]:checked').val();
another way
$('input:radio[name=theme]').filter(":checked").val()
This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.
$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
The following code is used to get the selected radio button value by name
jQuery("input:radio[name=theme]:checked").val();
Thanks
Adnan
For anyone who doesn't want to include a library to do something really simple:
document.querySelector('[name="theme"]:checked').value;
jsfiddle
For a performance overview of the current answers check here
I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.
With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.
To do the above now just replace the :radio with [type=radio].
So your answer now becomes for all versions of jQuery 1.8 and above:
$("input[type=radio][name=theme]").click(function() {
var value = $(this).val();
});
You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
You can use filter function if you have more than one radio group on the page, as below
$('input[type=radio]').change(function(){
var value = $(this).filter(':checked' ).val();
alert(value);
});
Here is fiddle url
http://jsfiddle.net/h6ye7/67/
<input type="radio" name="ans3" value="help">
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">
<input type="radio" name="ans2" value="test">
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">
<script type="text/javascript">
var ans3 = jq("input[name='ans3']:checked").val()
var ans2 = jq("input[name='ans2']:checked").val()
</script>
If you want a true/false value, use this:
$("input:radio[name=theme]").is(":checked")
Something like this maybe?
$("input:radio[name=theme]").click(function() {
...
});
When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.
I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:
$("input:radio[type=radio]").click(function() {
var value = $(this).val();
alert(value);
});
Cheers!
can also use a CSS class to define the range of radio buttons and then use the following to determine the value
$('.radio_check:checked').val()
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() {
if($(this).is(':checked'))
alert($(this).val());
});
Hope it helps..
$('input:radio[name=theme]').bind(
'click',
function(){
$(this).val();
});
You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.
You create RadioButton control in ASP.NET as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});

How to disable a textbox if particular radio button is clicked using jquery?

I have a html form in which I have four radio buttons and one text box. What I am trying to do is - Once I click Test4 radio button, I want to disable node textbox so that nobody can type anything in that. I don't want to hide it, I just want to disable it.
But if anybody clicks either Test1 or Test2 or Test3 then anybody can type anything into it.
Here is my jsfiddle
Is this possible to do using jquery?
Yes, this is possible; I'd suggest:
$('input[type="radio"]').change(function(){
$('#node').prop('disabled', this.value === 'test4');
});
JS Fiddle demo.
This sets the disabled property of the #node element to true (if the changed-element has the value of 'test4'), and to false if it does not.
Further to the discussion in comments (wherein, basically, the OP revealed that checking other input elements of type="radio" caused the #node element to become re-enabled), I've amended the HTML to offer a simple means of associating the appropriate inputs with the specific text-input, using data-affects. giving the following HTML:
<input type="radio" name="data" id="test1" value="test1" data-affects="nodes" />Test1
<input type="radio" name="data" id="test2" value="test2" data-affects="nodes" />Test2
<input type="radio" name="data" id="test3" value="test3" data-affects="nodes" />Test3
<input type="radio" name="data" id="test4" value="test4" data-affects="nodes" />Test4
Coupled with the amended jQuery:
$('input[type="radio"][data-affects]').change(function(){
$('#' + this.getAttribute('data-affects')).prop('disabled', this.value === 'test4');
});
JS Fiddle demo.
References:
change().
prop().
To your jsfiddle, add on the top of js this piece of code:
$("input:radio[name=data]").change(function () {
var checkedValue = $(this).val();
if (checkedValue == "test4") {
$("#node").prop("disabled", true);
} else {
$("#node").prop("disabled", false);
}
});
You can also call the radio group by id instead of name:
$("input:radio[id=data]").change(function () { //first line of code
Live example here: http://jsfiddle.net/pw9nZ/
Hope this helps you...
Theo.

Adding class to next element using jquery

I am having html like this:
<form>
<div class="row">
<input type="radio" class="radio">
<label>Text</label>
<input type="radio" class="radio">
<label>Type</label>
</div>
</form>
Now I need to apply a class to each label immediate after each <input type="radio">.
I am using jquery like this:
if($('input').hasClass('radio')){
$(this).next().addClass('radio-url');
}
I am trying to add class 'radio-url' to each <label> immediately after radio tag.
What mistake have I did in this?
You can use .siblings()
$('input[type="radio"]').siblings('label').addClass('radio-url');
DEMO
Or
$('input[type="radio"]').next('label').addClass('radio-url');
DEMO2
You can use next() function
$("input:radio").next('label').addClass("radio-url");`
Try:
$(':radio').next().addClass('radio-url');
jsFiddle example (I threw a text input in there so you can see that it works on only radio inputs)
This answer doesn't directly answer your question!
I believe that your label should have the for attribute so that the label is associated with the radio button. This allows the user:
To check the radio button by clicking the label!
If the input type is text, clicking the label focuses the text input
For accessibility reasons
HTML
<div class="row">
<input type="radio" class="radio" id="text"></input>
<label for="text">Text</label>
<input type="radio" class="radio" id="type"></input>
<label for="type">Type</label>
</div>
JQuery
Search the label using the radio element's ID.
$('input[type="radio"]').each(function(){
var radioId = $(this).attr("id");
$("label[for='" + radioId + "']").addClass('radio-url');
});
Fiddle: http://jsfiddle.net/78zAB/
DEMO
$('input.radio').each(function () {
$(this).next().addClass('radio-url');
})
Use CSS element+element selector:
$('input:radio + label').addClass('theClass')
http://jsfiddle.net/ttnUU/
Works optimal
$('input[type=radio]').next('label').addClass('radio-url');
http://jsfiddle.net/q76FJ/
You need to loop through all radio buttons:
$('input[type="radio"]').each(function(){
$(this).next().addClass('radio-url');
});
Or
$("input[type='radio'] + label").addClass('radio-url')
Fiddle Example
Example 2
Posting this as an answer as all of the others are using the incorrect selector, or don't specify the label in next():
$('input.radio').next('label').addClass('radio-url');
.. which will add the class radio-url to all label elements which come immediately after an input with the class radio

Uncheck an html checkbox with for label

I am using the following html to display a checkbox with an image:
<div class="testClass">
<input id="111" name="compare_checkbox" type="checkbox" />
<label for="111">
<i class="icon" aria-hidden="true"></i> <b>Compare</b>
</label>
</div>
I need to uncheck the checkbox in certain conditions. I am using the following jquery : $('#111')[0].checked = false;
This works fine if I don't have the label. When I have the label, I don't get any errors in console (either Chrome or Firefox), but the checkbox does not uncheck.
Just letting you know that you cannot have numbers leading your element ID. Please see Element ID in HTML Document ~ Naming Question. Hope this is helpful to you :)
Solution:
<div class="testClass">
<input id="one" name="compare_checkbox" type="checkbox" />
<label for="one">
<i class="icon" aria-hidden="true"></i> <b>Compare</b>
</label>
</div>
http://jsfiddle.net/tLsK7/
Checkbox states are best handled cross-browser with jQuery's prop function, regardless of whether or not the checkbox has an associated <label>.
$('#element').prop("checked", true); // Checks a checkbox.
$('#element').prop("checked", false); // Unchecks a checkbox.
working fine with for='111'
Here it is http://jsfiddle.net/spaipalle/umAsw/3/
$('#111').click(function(){
if($('#111').is(":checked")){
alert('checked');
$('#111')[0].checked = false; // uncheck it
}else{
alert('unchecked');
}
});
have you tried changing the id of the element? I don't think ID's can be made up of just numbers, or at least they can't start with a number

jQuery/JavaScript - Hide / Show Drop down box pending on Radio Button

I want to make it so that the drop-down is only displayed when the radio button (option 3) is clicked and have it hidden if either 1 or 2 is selected. What would be the best way to complete this? I have a little bit of experience with JavaScript and slim to none with jQuery but it seemed like it might be the way to go.
Thanks for any help,
Dan
Here is the HTML code I have as of now:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" /> Option 1 </label>
<label><input type="radio" name="select" /> Option 2</label>
<label><input type="radio" name="select" /> Option 3</label>
</div>
<div id="list" style="display: none;">
<label>Please Select From the List:
<select>
<option>True</option>
<option>False</option>
</select>
</label>
</div>
$(document).ready(function(){
$("[name=select]").change(function(){ // Whenever the radio buttons change
$("#list").toggle($("[name=select]").index(this)===2); // Only keep the list open when it's the last option (First option = 0, Third option = 2)
});
});
This code in action.
Assuming you are using jquery, as it sounds like it from your question, you could modify your HTML like so:
<p class="help">Selection:</p>
<div id='buttons'>
<label><input type="radio" name="select" id="option1" /> Option 1 </label>
<label><input type="radio" name="select" id="option2" /> Option 2</label>
<label><input type="radio" name="select" id="option3" /> Option 3</label>
</div>
<div id="list">
<label>Please Select From the List:
<select id="mySelect">
<option>True</option>
<option>False</option>
</select>
</label>
</div>​
</p>
Then you could write some jquery like so:
$(document).ready(
function()
{
$("#option1, #option2, #option3").click(
function()
{
if (this.id == "option3")
$("#mySelect").hide();
else
$("#mySelect").show();
});
});​
You can see it working here: http://jsfiddle.net/AVFuY/3/
EDIT: I removed the unneeded class and just used the id's so as to not confuse and add unnecessary code.
Since this is a fairly basic question, I think it'll be instructional to walk you through the jQuery documentation while I answer your question. If you know truly nothing about jQuery, I recommend following this short tutorial first -- it will make things much, much easier for you in the future: jQuery Documentation - Getting Started With jQuery
Your requirement is that something happens (in this case, another element is hidden/shown) when we click the radio buttons. There's two parts to this problem: first, we need to find the radio buttons, then we need to make something happen when we click it.
1. Finding the radio buttons
Take a look at the jQuery Selector documentation here: http://api.jquery.com/category/selectors/
As you can see, there's a specific pseudo-selector for radio buttons, ":radio". We want to select everything inside of the element with ID "buttons", so this is how the selector will look in total:
$("#buttons input:radio");
By the way, it's called a "pseudo-selector" because it filters items we've already selected (in this case, input tags inside of a div with id "button"). Pseudo-selectors always start with a ":".
2. Making something happen when we click them
Consult the jQuery Events reference here: http://api.jquery.com/category/events/
We want the ".click()" event here, clearly. Once we've selected our elements, we can apply a click handler to them like this:
$("#buttons input:radio").click(function() {
// make something happen here
alert("input button clicked: " + $(this).index());
});
Note that this will apply the same click handler to all three of the input buttons, but you can access the specific element that was clicked via the "this" keyword. Wrapping $() around it makes it into a jQuery selection rather than just a Javascript object and allows us to call jQuery functions on it.
3. Hiding and showing the list element conditionally
Let's extend the code above to actually hide and show that other div, depending on which item was clicked. We're going to refer to the jQuery Effects documentation so that we can make hiding and showing it exciting: http://api.jquery.com/category/effects/
The functions we'll be using are ".slideUp()", which hides an element, and ".slideDown()", which shows it. We'll also be using the ".index()" function I used in the previous example to figure out which button was clicked, although I recommend giving the button a unique ID in the future so that your code isn't dependent on the order of the buttons. Here's the final code:
$("#buttons input:radio").click(function() {
// if it was the third button (0-indexed, so the 3rd one is index 2)...
if ($(this).index() == 2) {
// display the element with ID "list"
$("#list").slideDown();
}
else {
// hide the element with ID "list"
$("#list").slideUp();
}
});
Sorry for the length of this answer, but hopefully it was more conducive to your understanding of jQuery than "copy and paste this 3-line super-compact solution".
<label><input type="radio" name="select" onclick="document.getElementById('list').style.display=this.checked?'':'none'" /> Option 3</label>
Without changing your markup:
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
if (myindex == 2)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});
EDIT: Another option: just show it on the last button in the list.
$(function()
{
$("#list").hide();
$("#buttons input:radio[name=select]").click(function()
{
var myindex = $("#buttons input:radio[name=select]").index(this);
var lastone = $("#buttons input:radio[name=select]:last").index("#buttons input:radio[name=select]");
if (myindex == lastone)
{
$("#list").show();
}
else
{
$("#list").hide();
};
});
});

Categories