There is a problem with jquery mobile, form element- checkbox. So, i have a code in .cs file:
email = Request.Form["Email"];
password = Request.Form["password"];
rememberMe = Request.Form["remember_me"].AsBool();
As usually, this code have to fill variables with form data, but state of jquery mobile checkbox doesn't use 'checked' HTML markup. (http://jquerymobile.com/test/docs/forms/checkboxes/index.html)
It's just change class in label like 'ui-checkbox-off/ui-checkbox-on'.
So, is it possible without big amount of code to check state of checkbox, created by jquery mobile?
Thx.
Maybe you can do something like this?
<div data-role="fieldcontain" id="divCheckbox">
<fieldset data-role="controlgroup">
<legend>Agree to the terms:</legend>
<input type="checkbox" name="checkbox-1" id="checkbox-1" class="custom" />
<label for="checkbox-1">I agree</label>
</fieldset>
</div>
JS
$("#divCheckbox").click(function() {
var checkbox = $(this).find("input[type='checkbox']");
var label = $(this).find(".ui-checkbox-on");
checkbox.prop("checked", label.length);
});
Not 100% sure but at least the DOM changes (see http://jsfiddle.net/rcSza/4/) Otherwise you can do something with a hidden field..
Related
Here is my html:
<input type="checkbox" value="1" name="Visual" id="visual">
<input type="checkbox" value="1" name="Tuberculosis" id="Tuberculosis">
<input type="checkbox" value="1" name="Skin" id="Skin">
<script type="text/javascript">
$('#checkbox-value').text($('#checkbox1').val());
$("#checkbox1").on('change', function() {
if ($(this).is(':checked')) {
$(this).attr('value', 'true');
} else {
$(this).attr('value', 'false');
}
$('#checkbox-value').text($('#checkbox1').val());
});
</script>
Here is my view:
Visual = request.POST['Visual']
Tuberculosis = request.POST['Tuberculosis']
Skin = request.POST['Skin']
V_insert_data = StudentUserMedicalRecord(
Visual=Visual,
Tuberculosis=Tuberculosis,
Skin=Skin
)
V_insert_data.save(
Why is it every time I save the data to my database, the Visual, Tuberculosis and Skin are automatically checked even though I didn't check it when I was saving it? Or I think my javascript is wrong?
You don't need $('#checkbox-value').text($('#checkbox1').val());, unless you have such element on the page
which you haven't shown us.
You can't define more than one element on the same page with the same id.
(Same goes for the name attribute).
Use different ids as shown in my code and match the chekboxes by class/name.
Don't put value="1" inside your checkboxes.
Put your jQuery code inside a $(function() { }); which is an alias for $( document ).ready().
More info here.
Don't use bare request.POST values, use the sanitized self.cleaned_data['var_name'] instead.
I don't think it's a good idea to have param names with capital letters (this is just a note, it will not impact the functionality). According
to Python's PEP 8, only classes should start with a capital letter.
Frontend:
<input type="checkbox" name="Visual" id="checkbox1" class="checkbox-js-trigger-class">
<input type="checkbox" name="Tuberculosis" id="checkbox2" class="checkbox-js-trigger-class">
<input type="checkbox" name="Skin" id="checkbox3" class="checkbox-js-trigger-class">
<script type="text/javascript">
$(function() {
$(".checkbox-js-trigger-class").on("change", function(){
var new_val = $(this).is(':checked') ? 1 : 0;
$(this).val(new_val);
});
});
</script>
Backend:
It's best to use Model Form:
class StudentUserMedicalRecordForm(ModelForm):
class Meta:
model = StudentUserMedicalRecord
fields = ['Visual', 'Tuberculosis', 'Skin']
Because you have default value given as "1" here
<input type="checkbox" value="1" name="Visual" id="visual">
And also there is no element with id = "checkbox1" or id = "checkbox-value" which are referenced in your script.
Checkbox inputs are actually a little strange and work differently than how you think they work.
You don't need jQuery to handle the case when a checkbox has been changed. The browser and HTML handle that for you. (Sort of like how you don't need to listen for keys being pressed while the user is focused on a input type="text" to make letters show up in the text box.)
Instead, what happens is if the user checks the checkbox, the input will have an attribute called checked. It can look something like this .
The checkbox input tag also has two other attributes name and value. These are what get sent to the server when the form is submitted. BUT it only sends the name and value pair for the checkboxes that are checked! For the checkboxes that are not checked, it sends nothing. So if every checkbox has a name and value you can think of it as a key-value pair. If the check box is checked, it will send key=value to the server. You are allowed to have more than one value for a single key if you designate the name as being the name of an array.
So imagine you have a form like this:
<input type="checkbox" name="disease[]" value="tuberculosis" checked>
<input type="checkbox" name="disease[]" value="chickenpox" checked>
<input type="checkbox" name="disease[]" value="smallpox">
<input type="checkbox" name="needs_medicine" value="true" checked>
<input type="checkbox" name="recovered" value="whatevervalue">
When that form is submitted, the server will receive something that looks like "disease=[tuberculosis,chickenpox]&needs_medicine=true"
Notice that smallpox and recovered are not mentioned because they are not checked. Also notice that it's not super important what you put as the value of a checkbox that is not a multiple choice checkbox (in this example, needs_medicine) because the value that gets sent to the server will always either be the value of the checkbox (in this case, the string "true").
I am generating a list of checkboxes & radio buttons based on data coming from a server. The page is a Handlebars template using Ember. To generate my list on the page, I am using the following line of code:
document.getElementById('radioList').innerHTML = newHtml;
This works fine if newHtml is set to something like:
<li><input type="radio" id="radio1" name="radio /><label for="radio1">List item one</label></li>
However, I'd like events to be triggered based on these radio buttons (or checkboxes) being selected or unselected - and after some googling, it would seem using Handlebars helpers is the way to go. But when I try to insert the radio button using handlebars, with the newHtml set as such:
<li>{{input type="radio" id="radio1" name="radio }}<label for="radio1">List item one</label></li>
The text just appears rather than a radio button itself. Looking further into this seems to suggest that the Handlebars template I'm inserting into needs recompiled? I may be wrong, but I've spent quite a bit of time searching for answers to this problem and can't seem to find them. Any help would be appreciated!
This may help you to do this with jQuery.
Triggering using button for example
<h2>Click and select radio button</h2>
<input type="button" id="btn" value="Generate"/>
<input type="hidden" value="1" id="hid" />
JQUERY
$("#btn").click(function(){
var generatedradios=$("#hid").val();
var str='<input type="radio" class="generated" data-generated="'+generatedradios+'" id="radio1" name="radio" />';
$("#hid").val(Number(generatedradios)+1);
$("body").append(str);
});
$(document).on("change",".generated",function(){
alert($(this).attr("data-generated"));
});
FIDDLE
http://jsfiddle.net/Isakkiraj/wLg1p8as/
I need to get the class attribute of checked radio button, with name="radio".
Used the code that's working fine in Firefox, but fails in IE.
val = $('input:radio[name=radio]:checked').attr('class');
How can i accomplish this?
There is no psuedo-class :radio. I think you meant [type=radio].
As comments says, I think you should use type instead of name. But i think you have named your input as radio because you can find this specific input. If you just use type selector you will catch every single selected radio input on page.
<input type="radio" name="radio" class="ey" /> Male<br />
So, if your page have more forms, you should specify a parent or form to avoid conflicts. Set a id for your form and try to find it by form id and radio type like this:
<form id="myForm">
<input type="radio" name="radio" class="ey" /> Male<br />
</form>
val = $("#myform input[type='radio']:checked").attr('class');
I hope it can help you :)
I have an HTML form with some radio buttons like these:
<form action = "/somecomplicatedurl" method="post">
<ul id="category_list">
<li>
<label for="Foo">
<input type="radio" name="category" id="foo" value="foo" onclick="this.form.submit()" />
Foo</label>
</li>
<li>
<label for="Bar">
<input type="radio" name="category" id="bar" value="bar" onclick="this.form.submit()"/>
Bar</label>
</li>
<li>
<label for="Spam">
<input type="radio" name="category" id="spam" value="spam" onclick="this.form.submit()"/>
Spam</label>
</li>
</ul>
</form>
On the onclick event, I would like to add a query string to the action /somecomplicatedurl adding the selected category.
For example, clicking the category spam should fire an HTTP post with an action like this:
/somecomplicatedurl?category=spam
Javascript or jQuery are both valid.
EDIT:
the category value is already passed correctly to the server;
I just need that, once the radio button is clicked, the url displayed in the browser address-bar contains the selected category. *
* I would like to avoid to add another redirect because I'm currently handling different cases on that /somecomplicatedurl route
The mixing of POST/GET variables is considered as a poor form. Why not dynamically set a hidden form field:
<input type="hidden" id="category" name="category" value="spam" />
instead?
Your onclick would become:
onClick="document.getElementById('category').value = this.value; this.form.submit();"
if it's just a display issue, then
onclick="this.form.action='/somecomplicatedurl?category=' + this.value; this.form.submit();"
Sorry, misunderstood your question at first.
You can change the form action by adding
document.this_form.action = "somecomplicatedurl?category=span";
to your onClick-event, before submitting.
Seems to me that using method "GET" in the form tag would accomplish what you want, or am I misunderstanding the question...
Changing the form method to get is probably the easiest, but on the off-chance that it's a little more complicated than that, here's some jQuery. Take out those inline scripts and write something like this:
$(function () {
$('#category_list input').change(function () {
var jQthis = $(this),
jQform = $(this).parents('form'),
currentAction = jQform.attr('action'),
// This removes the current query, if you've added one.
newAction = currentAction.split('?').shift();
// Work out the new action and set it.
newAction += jQthis.val();
jQform.attr('action', newAction);
// Submit the form, since your previous handlers were doing that.
jQform.submit();
});
});
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();
});