Auto disable other checkboxes using html.checkboxfor once one is selected - javascript

I am trying to disable other checkboxes on selection of one checkbox and enable again if this has again been de-selected.Below is a snippet of code I found that worked during an example fiddle for a standard checkbox but I have not been able to replicate this for a checkboxfor, can someone please recommend the changes I need to make in order for this to work in a checkboxfor?
<script>
$('#chkItems').change(function () {
$(this).siblings('#chkItems').prop('disabled', this.checked)
});
</script>
And below is my checkboxfor where I am calling this
#Html.CheckBoxFor(modelItem => item.IsDisplayImage, new { id = "chkItems" })

You can use this code if want to persist using checkboxes otherwise its better to use radio button instead
HTML
<label class="checkbox-inline check">
<input type="checkbox" name="skills" id="radio" value="1"> 1
</label>
<label class="checkbox-inline check">
<input type="checkbox" name="skills" value="2"> 2
</label>
<label class="checkbox-inline check">
<input type="checkbox" name="skills" value="3"> 3
</label>
JS:
$('.check input:checkbox').click(function() {
$('.check input:checkbox').not(this).prop('checked', false);
});
Check this jsfiddle for the demo
You can use radio buttons as :
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>

Okey. For example you have model ForRadioButtonsModel like
public class ForRadioButtonsModel
{
public int Id { get; set; }
public bool IsDisplayImage { get; set; }
}
On View You pass Collection of this models or model that contains this collection
return View((List<ForRadioButtonsModel>) collection);
Than In view you can do next to create RadioGroup
#foreach (var item in Model) <-- Model is of type List<ForRadioButtonsModel>
{
#Html.RadioButtonFor(m => item.IsDisplayImage, item.IsDisplayImage)
}
This will render next HTML
<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="True">
<input checked="checked" id="item_IsDisplayImage" name="item.IsDisplayImage" type="radio" value="False">
So You will have radioButtons with same name, but with different values

Related

How to serialize form, but instead of an input's values get the input's ID

Here is a jsfiddle for reference.
I need to serialize a form, so when a user hits submit I get all the ID's of the inputs the user has selected in a "serialized" format. I have used this to get the form ID's:
$("button").click(function(){
$("div").text($("form").serialize());
});
The problem is, it gives me the form's values. How do I modify this code to give me the IDs of the selected inputs instead of the values?
This is the HTML:
<form action="">
Choose one:<br>
<input type="radio" name="name" id="option1" value="2.00">Option 1<br>
<input type="radio" name="name" id="option2" value="2.00">Option 2<br>
<input type="radio" name="name" id="option3" value="2.00">Option 3<br>
</form>
<button>Serialize form</button>
<div></div>
So for example, when the button is clicked, the serialized output should say either "option1" "option2" or "option3", not "2.00" "2.00" or "2.00".
Edit
I was hoping there was a way to incorporate ".attr('id')" into the serialization, I have
$(document).ready(function() {
$('input').on('change', function () {
alert($(this).attr('id'));
});
});
This alerts me the ID's, but I cannot find a way to incorporate it into the serialization.
Another way of implementation using Array.from
$(document).ready(function () {
$('#form').bind('submit', function () {
var serialize = Array.from($('input:checked'), e => "id=" + e.id).join('&');
console.log(serialize);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="" id="form">
Choose one:<br>
<input type="radio" name="name" id="option1" value="2.00">Option 1<br>
<input type="radio" name="name" id="option2" value="2.00">Option 2<br>
<input type="radio" name="name" id="option3" value="2.00">Option 3<br>
<br/>
Choose one:<br>
<input type="checkbox" name="name1" id="option1" value="2.00">Option 1<br>
<input type="checkbox" name="name2" id="option2" value="2.00">Option 2<br>
<input type="checkbox" name="name3" id="option3" value="2.00">Option 3<br>
<input type="submit" name="submit" value="Serialize form" id="submit" />
</form>
This function gives a the value of ID instead of name, hope this is what you needed.
Snippet has two forms one with radio and other with check boxes
function getSerialize(form)
{
var selected = $('form input:checked');
var serialized = '';
selected.each(function(){
if(serialized != '')serialized += '&';
serialized += $(this).attr('name') + '=' + $(this).attr('id');
});
return serialized;
}
$('#button1').click(function(){
console.log(getSerialize('#form1'));
});
$('#button2').click(function(){
console.log(getSerialize('#form2'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h5>For radio</h5>
<form id="form1" action="">
Choose one:<br>
<input type="radio" name="name" id="option1" value="2.00">Option 1<br>
<input type="radio" name="name" id="option2" value="2.00">Option 2<br>
<input type="radio" name="name" id="option3" value="2.00">Option 3<br>
</form>
<br>
<button id="button1">Serialize form</button>
<br>
<h5>For checkboxes</h5>
<form id="form2" action="">
Choose one:<br>
<input type="checkbox" name="name1" id="option1" value="2.00">Option 1<br>
<input type="checkbox" name="name2" id="option2" value="2.00">Option 2<br>
<input type="checkbox" name="name3" id="option3" value="2.00">Option 3<br>
</form>
<button id="button2">Serialize form</button>
Classical XY problem.
You don't need another serialization method. You just have to put your option1, option2 and option3 into value attributes, instead of id. This way the usual serialization will return to you what you desire.
If the answer from Styx didn't satifies your needs then think you'll have to come up with your own "serialization". The one from jQuery is meant to serialize the data in a manner much like if you where to hit submit on a form.. When you hit submit in html, only the selected values of a radiobutton are sent.
A "dirty" way that works in your case is the following. But if you use it like that you are not dynamic in any way. I just get the id and the name and add it together as string (not urlencoded or anything else in this example though...).
Please read the following for a practical solution:
However you could place those radios outside the form. When someone submits the form you use preventDefault() to stop submission and instead append the radio id to the serialized form data. An example would be serialized_data += "&name=" + encodeURIComponent(THE_ID);.
$(document).ready(function(){
$("button").click(function(){
var radio = $('input[name="name"]:checked');
$("div").text(radio.prop('name') + '=' + radio.prop('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
Choose one:<br>
<input type="radio" name="name" id="option1" value="2.00">Option 1<br>
<input type="radio" name="name" id="option2" value="2.00">Option 2<br>
<input type="radio" name="name" id="option3" value="2.00">Option 3<br>
</form>
<button>Serialize form</button>
<div></div>

JQuery "onchange" event on just one checkbox among multiple in a group based on label text

I have a group of checkboxes as -
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>
<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>
<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>
Due to variable values of id and name, I'm unable to handle onclick event on checkbox with label One.
I've tried this which works fine, but I don't want to use check_1 since the number 1 is variable and could be changed.
$("#check_1").change(function() {
alert('Checkbox One is clicked');
});
How do I do this as I have no access to modify the html ?
You can use a selector like this $('input[type="checkbox"]:has(+ label:contains("One"))') with the label text as below,
$('input[type="checkbox"]:has(+ label:contains("One"))').on('click', function(){
alert('Checkbox One is clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>
<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>
<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>
Looks like your only criteria is the text of the label so you could target the input based on that label like :
$('label:contains("One")').prev('input:checkbox').change(function(){
console.log('One changed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>
<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>
<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>
Hope this helps.

Change the position of parsley-errors-list in parsleyjs

I am using parsleyjs.org to validate my forms.
The plugin creates a ui.parsley-errors-list when an input has a validation error.
The problem is that the .parsley-errors-list is being placed just after the form element's "input, textarea, radio etc.." breaking my layout as follows:
<fieldset>
<p>Checkboxs with a max</p>
<label class="checkbox parsley-error">
<input name="checkbox2" type="checkbox" required="" data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" data-parsley-id="5492"> <span></span>
<p>Normal</p>
</label>
<ul class="parsley-errors-list filled" id="parsley-id-multiple-checkbox2">
<li class="parsley-required">This value is required.</li>
</ul>
<label class="checkbox">
<input name="checkbox2" type="checkbox" data-parsley-multiple="checkbox2" data-parsley-id="5492"> <span></span>
<p>Normal</p>
</label>
<label class="checkbox">
<input name="checkbox2" type="checkbox" data-parsley-multiple="checkbox2" data-parsley-id="5492"> <span></span>
<p>Normal</p>
</label>
</fieldset>
Instead, the .parsley-errors-list need to be positioned to be the last child/element within the container <fieldset>.
Is this achievable?
You can set the error container with (at least) two ways.
Change the container with DOM attributes
In cases where you only have one input (or group of inputs, like you do) and you want to change the container of the errors on those inputs, you can use data-parsley-errors-container="#element" (see the docs). Here is an example (jsfiddle demo)
<fieldset>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox1" required data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option1" data-parsley-errors-container="#checkbox-errors" /> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox2" data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option2" /> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option3" /> 3
</label>
<div id="checkbox-errors"></div>
</fieldset>
Note the attribute data-parsley-errors-container="#checkbox-errors" on the first checkbox and the element <div id="checkbox-errors"></div> at the end of the fieldset.
In this case you don't need to add the data-parsley-errors-container to all checkboxes because you're "grouping" them with data-parsley-multiple="checkbox2".
Set a custom configuration to be used by Parsley
In cases where you have a few or all inputs and you want to change the position of the default container. Lets say all your fields are placed inside a fieldset and you want to display the errors at the end of the fieldset.
This solution allows you to change the default container for each field (jsfiddle demo)
<fieldset>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox1" required data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option1" /> 1
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox2" data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option2" /> 2
</label>
<label class="checkbox-inline">
<input type="checkbox" id="inlineCheckbox3" data-parsley-maxcheck="2" data-parsley-multiple="checkbox2" value="option3" /> 3
</label>
<div id="checkbox-errors"></div>
</fieldset>
<script>
$(document).ready(function() {
var parsleyConfig = {
errorsContainer: function(parsleyField) {
var fieldSet = parsleyField.$element.closest('fieldset');
if (fieldSet.length > 0) {
return fieldSet.find('#checkbox-errors');
}
return parsleyField;
}
};
$("form").parsley(parsleyConfig);
});
</script>
In this solution we've added the element <div id="checkbox-errors"></div> before the end of the fieldset and changed the errorsContainer option of Parsley. If our element is inside a fieldset the errors will be displayed inside the #checkbox-errors.
Based on this example, you are also able to set the same container for all fields. In this case your options would be something like this (jsfiddle demo):
var parsleyConfig = {
errorsContainer: function(parsleyField) {
return $('#errors');
}
};
For this kind of UI errors in the parsley js.
You can use the data-parsley-errors-container custom validator for placing the parsley error message as per your form needs.
<div>
<div class="radio radio-primary">
<input type="radio" id="cellPhone1" value="1" name="rd_cell_phone" required="" data-parsley-error-message="Please select an option" data-parsley-errors-container="#cell-phone-validation-error-block">
<label for="cellPhone1"> Yes </label>
</div>
<div class="radio radio-primary">
<input type="radio" id="cellPhone0" value="0" name="rd_cell_phone" required="" data-parsley-error-message="Please select an option" data-parsley-errors-container="#cell-phone-validation-error-block">
<label for="cellPhone0"> No </label>
</div>
</div>
<div class="margin-top10" id="cell-phone-validation-error-block"></div>
Try this:
$.listen('parsley:field:error', function(fieldInstance){
var fieldName = fieldInstance.$element.attr('name');
var field = $('input[name="'+fieldName+'"]');
var fieldWrapper = field.parents('fieldset');
if (fieldWrapper.find('.errors_container').length > 0) {
setTimeout(function(){
fieldWrapper.find('.errors_container').append(fieldWrapper.find('.parsley-errors-list'));
},100);
}
});
$('form').parsley();
}
Use class, because it works for many fields.

how to clear the previous checked value

I am passing the selected value to the jquery from jquery in passing to the url to the next page, this is how my check box looks like:
<label class="checkbox">
<input type="checkbox" value="male" id="gender" name="gender" /> Male
</label>
<label class="checkbox" style="margin:-25px 0 0 100px">
<input type="checkbox" value="female" id="gender" name="gender" /> Female
</label>
<label class="checkbox" style="margin:-20px 0 0 205px">
<input checked type="checkbox" value="all" id="gender" name="gender"> All
</label>
my jquery:
var gender = $('input[name=gender]:checked').map(function(){
return $(this).val();
}).get();
alert(gender);
My problem is for example :
When I select the gender male it passes to jquery as 'male,' but my problem is here when I unchecked the male and check the female then it passes to jquery as female,male, it is not passing the value which is selected now it is passing the value with pervious one, can any one guide me how to solve this.
Use jQuery change event as follows
$('input[name=gender]').on('change',function(){
var gender = $('input[name=gender]:checked').map(function(){
return $(this).val();
}).get();
alert(gender);
});
DEMO
First of all: an id must be unique, as soon as there are two elements with same id (like "gender"), results are arbitrary random.
And: use radio button and you're done w/o any JS or jQuery:
<label class="checkbox">
<input type="radio" value="male" id="gender_m" name="gender" /> Male
</label>
<label class="checkbox" style="margin:-25px 0 0 100px">
<input type="radio" value="female" id="gender_f" name="gender" /> Female
</label>
<label class="checkbox" style="margin:-20px 0 0 205px">
<input checked type="radio" value="all" id="gender_a" name="gender"> All
</label>
And if you want the radios look like check boxes, see this post

Disable radio button according to selected choice

I want to disable some radio button in a html form according to selected choices, if he select the first choice in the first radio button group the 2 choices in the second radio button group will be enabled, if not they will be disabled, here's my code:
<script language="javascript">
function RadioMeuble() {
if (document.f.radio1[0].checked) {
alert("Vous avez choisi la proposition " + document.f.radio1[0].value);
document.f.radio2[0].disabled = false;
document.f.radio2[1].disabled = false;
} else {
document.f.radio2[0].disabled = true;
document.f.radio2[1].disabled = true;
}
}
}
</script>
<input type="radio" name="radio1" value="L" id="radio1" onBlur="RadioMeuble()">á louer</label>
<br>
<label>
<input type="radio" name="radio1" value="V" id="radio1">á vendre</label>
</p>
<p>Superficie
<label for="textfield"></label>
<input type="text" name="superficie" id="Superficie">en Km ²</p>
<p>Prix
<label for="textfield2"></label>
<input type="text" name="prix" id="Prix">en DT</p>
<p>Meublé
<input type="radio" name="radio2" id="radio2" value="oui" disabled>Oui
<input type="radio" name="radio2" id="radio2" value="non" disabled>
<label for="radio2"></label>
<label for="radio"></label>Non</p>
It doesn't work. What's wrong with it?
There's a "}" too much in your code (last one).
Don't use the onblur EventHandler. You should use onchange or onclick instead.
<input type="radio" name="radio1" value="L" id="radio1" onchange="RadioMeuble()">
or
<input type="radio" name="radio1" value="L" id="radio1" onclick="RadioMeuble()">
HTH,
--hennson
Well, first of all, you have an extra "}" Second, you probably want the click event instead of the blur event. And you want it on both radio buttons. Next what is document.f? That's not a variable. Next, even if it were, I'm not aware of a browser that lets you use form elements like you are trying to. E.g., document.f.radio2[0].disabled. Also, your radio button should have unique ID names.
See: http://jsfiddle.net/vzYT3/1/ for something more sensible.
You could improve your coding a little, check this example:
<input type="radio" id="r1-1" name="r1" value="1">
<label for="r1-1">Option 1</label>
<input type="radio" id="r1-2" name="r1" value="2">
<label for="r1-2">Option 2</label>
<hr />
<input type="radio" id="r2-1" name="r2" value="a">
<label for="r2-1">Option A</label>
<input type="radio" id="r2-2" name="r2" value="b">
<label for="r2-2">Option B</label>
and
function byId(id) {
return document.getElementById(id);
}
window.onload = function() {
byId('r1-1').onchange = byId('r1-2').onchange = function() {
byId('r2-1').disabled = byId('r2-2').disabled = byId('r1-1').checked;
}
}
Running example at: http://jsfiddle.net/5Mp9m/
It wouldn't be a bad idea to use a javascript library like Jquery.

Categories