I am trying to make a selector available, only if a check box, or more than one are checked. The selector should go back to being disabled if the user unchecks all the checkboxes.
I was trying to implement my solution from this response (that it works perfect for one checkbox paired with any other selector) ; however, when I implement it like this:
$(document).ready(function(){
var enable_sel = function(){
$("#pizza_kind").prop("disabled", !$(":checkbox").prop("checked"));
};
enable_sel();
$(":checkbox").change(enable_sel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="p1" name="p1">
<input type="checkbox" id="p2" name="p2">
<input type="checkbox" id="p3" name="p3">
<select name="pizza_kind" id="pizza_kind">
<option>(choose one)</option>
<option>"Hawaian"</option>
<option>"Peperonni"</option>
<option>"Another"</option>
</select>
</form>
I got the selector disabled, but it seems that is only reacting to the first checkbox, not the rest of them.
I couldn't make this work in the javascript/html snippet, don't know why.
I am currently using Flask and jquery 3.6.0
What am I doing wrong?
When you read a prop from a collection it will only ever select the first one. It is not going to randomly pick the one you want, so you need to tell it exactly what to pick.
So select the checked checkboxes and check the length. To do this use :checked in the selector and it will pick the ones that are checked.
$(document).ready(function(){
var enable_sel = function(){
$("#pizza_kind").prop("disabled", !$(":checkbox:checked").length);
};
enable_sel();
$(":checkbox").change(enable_sel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" id="p1" name="p1">
<input type="checkbox" id="p2" name="p2">
<input type="checkbox" id="p3" name="p3">
<select name="pizza_kind" id="pizza_kind">
<option>(choose one)</option>
<option>"Hawaian"</option>
<option>"Peperonni"</option>
<option>"Another"</option>
</select>
</form>
Related
I want to create a simple html form with different inputs element. The questions and the possible choices for each question are stored in a database. The idea is to render form and child input elements with PHP, so a simple PHP function will take care of typesetting according to whether is type="text" or type="radio":
<form>
First name: <input id="1" type="text" name="firstname">
Last name: <input id="2" type="text" name="lastname">
<input id="3" type="radio" name="sex" value="male">Male
<input id="4" type="radio" name="sex" value="female">Female
<div id="div_5_optional">
Maiden name: <input id="5" type="text" name="maidenname" disabled="disabled">
</div>
</form>
Now, by default input id="5" will be disabled. But I also want to remove it. I am able to get it with JavaScript by loading in my header (although I can't guarantee the move to be smart)
<script>
$(document).ready(function(){
$("[disabled=disabled]").parent().remove();
});
</script>
So far so good, the div element is removed. Yet, I want to put the element back and in the original position when the radio button corresponding to Female is clicked. I added in the header, just below the previous js script this
<script type='text/javascript' src='scripts/enable_elements.js'></script>
which loads this function
// enable_elements.js
$(document).ready(function(){
$('#4').click(function(){
$( '#5' ).prop( "disabled", false );
});
});
Yet the all thing doesn't work. I guess the problem could be the my ready(function)s are only loaded once at the beginning and then put to sleep? Should I structure my form differently?
You do not want to remove(), instead you want to hide().
$(document).ready(function(){
$("#5").hide();
});
Also you want to handle the click on #3:
$('#3').click(function(){
$( '#5' ).attr("disabled", "disabled").hide();
});
$('#4').click(function(){
$( '#5' ).attr("disabled", "").show();
});
Note: I kept the "disabled" attribute, but really you don't need it since it will be hidden when unselectable...
If you remove the #5, then it's lost and you cannot show it again. So clicking on Male, then Female, back on Male, and on Female again... would not work.
you need to create a eventhandlers for the female and male checkbox that call your function and displays or hides the field
Let's assume, a database contains entries for cars in many models, colours and with 2, 4 and 5 doors.
The task: Create a search form which lets the user pick both model, colour and number of doors, using only radio buttons. Every time the user selects a radio button, the search result should be updated. No Submit-Button.
The HTML-Code:
<form id="searchform">
<div>
<input id="car_model1" type="radio" name="model" value="bmw"> BMW
<input id="car_model2" type="radio" name="model" value="peugeot"> Peugeot
<input id="car_model3" type="radio" name="model" value="fiat"> Fiat
</div>
<div>
<input id="car_colour1" type="radio" name="colour" value="white"> White
<input id="car_colour2" type="radio" name="colour" value="red"> Red
<input id="car_colour3" type="radio" name="colour" value="blue"> Blue
</div>
<div>
<input id="car_door1" type="radio" name="door" value="2"> Two
<input id="car_door2" type="radio" name="door" value="4"> Four
<input id="car_door3" type="radio" name="door" value="5"> Five
</div>
</form>
<div id="searchresult"></div>
Now, I thought, I could use the jQuery change() function to catch the users click and then send a request via post() to the database. But somehow I can't make it work. Here is my attempt:
The Javascript-Code
$("[id^=car]").change(function() {
var data = $("#searchform").serialize();
$.post("process_data.php", data, function(response) {
$("#searchresult").html(response);
});
});
Of course there is PHP-Code to process the request, but the problem is that the Javascript is not executed. The change-Event does not work. I also tried it with click() and keyup(). Same negative result.
I am quite new to jQuery and Ajax and right now I have no idea what is wrong. Maybe you can tell me where my error is.
Just try this,
$("input[id^=car]").change(function() {
I will not say that your selector is wrong. But using an element name before the attribute selector is a good practice.
Fiddle : DEMO
Another day and after a good sleep I tried it again and this time I found the source of the problem: I load the script in the <head> part of my HTML. Therefore I need to make sure, the document is fully loaded, using the ready() function, otherwise the change() function does not work:
$(document).ready(function() {
$("input[id^=car]").change(function() {
var data = $("#searchform").serialize();
$.post("process_data.php", data, function(response) {
$("#searchresult").html(response);
});
});
});
I have four radio buttons. If I select the last radio button then one textbox is appearing. I handled this scenario by jquery. Now I want to validate in such a way that if user gets this textbox means if user checked the last radio button, then he should provide some text.But in my case, if I check any one of the radio button, its telling to provide some text. The code is like:
<input type="radio" name="bus_plan" id="smallBtn" value="1" />1
<input type="radio" name="bus_plan" id="smallBtn" value="2" />2
<input type="radio" name="bus_plan" id="smallBtn" value="3" />3
<input type="radio" name="bus_plan" id="smallBtn" value="Promotional" />
<span class="plantxt"><a style="cursor:pointer;" onclick="popup('popUpDiv')">Promotional Plan</a> (Please enter a promotional code)</span>
<div class="reg-line" id="pr_code_id" style="display:none">
<div class="reg-linea" align="left">Promotional Code: <sup>*</sup></div>
<input type="text" name="bus_prcode" id="bus_prcode" class="reg-line-input" value="Promotional Code" onblur="if(this.value=='') this.value='Promotional Code'" onClick="if(this.value==this.defaultValue) this.value='';" />
<br />
<div>
<div id="promotionalbox" style="display:none;font-size:13px;clear:both"></div>
</div>
</div>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input:radio[name=bus_plan]").click(function(){
var values = $(this).val();
if(values == 'Promotional'){
$('#pr_code_id').show();
}else{
$('#pr_code_id').hide();
}
});
});
</script>
and in js if I alert the value of document.getElementById('bus_prcode').value then always it is showing Promotional code, which is only for last radio button value.
Your code is a bit of a mess which is the root of this problem. Remember, one element per ID.
You may also find it helpful to look at jQuery .is(), for example:
$('input[value="Promotional"]').is(':checked')
n.b. I do not suggest the above, you should use identifiers in the appropriate way first.
Also worth noting that your code works fine for me using Chrome. See an example (which I have expanded for you) here: http://jsbin.com/ofujal/3/
You should not have an element with the same ID (your radio buttons). Also, you're getting the textbox by running document.getElementById('bus_prcode') and not the radio button. You should give a unique ID to your last radio button, e.g. btnPromotional, then bind click to it:
$("#btnPromotional").click(...)
Example need for ajax, where on selecting a radio button will dynamically produce drop down
If you use or can use jQuery, this is the way I would do it:
Having this HTML:
<input type="radio" name="myradio" value="foo" />
<input type="radio" name="myradio" value="bar" />
<input type="radio" name="myradio" value="baz" />
and assuming you have a page "your_page.php" that returns the list to populate the drop down as JSON, do this:
$("input[#name='myradio']").change(function(){
var selected_value = $("input[#name='myradio']:checked").val();
$.getJSON("your_page.php", { value: selected_value }, populate_dropdown);
});
function populate_dropdown(items) {
// "items" is the ajax-loaded list based on the selected radio button.
// Clear the drop down, populate it and show it if hidden.
}
could you explain yourself a little more?
You need an example where if you click on a radio button and select is showing?
if yes you don't need ajax.
My radio: <input type="radio" name="YOUR_RADIO" onclick="document.getElementById('selectfield').style.display='';" />
<div id="selectfield" style="display:none">
<select><option>option</option></select>
</div>
good luck ...
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();
});