i am trying to loop through the radio buttons by name with 'each' function..the each function is not working and it is applying the logic only once and it is not looping for the next time..
My use case is, when user selects value from the select dropdown, needs to enable both the radio buttons and if the user deselects the dropdown- needs to disable back..
Here in my case, each function is looping only once and after that it is getting exit from it..Need help in figuring disable/enable based on dropdown selection..
html code:-
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser" value="anyUser" name="authPermission" id="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser" value="groupUser" name="authPermission" id="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder" id="authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
jquery:
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(){
$("#authPermission").prop('disabled',false);
$("#authPermission").prop('checked',false);
});
}
else{
$("#authPermission").each(function(){
$("#authPermission").prop('disabled',true);
$("#authPermission").prop('checked',false);
});
}
});
You cannot have more than one element with the same ID. So, I would change your code by removing the id attribute and putting a new value for the class attribute, then fetch the object using jquery class selector.
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser authPermission" value="anyUser" name="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser authPermission" value="groupUser" name="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
And jQuery code :
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(elemId, elem){
$(elem).prop('disabled',false);
$(elem).prop('checked',false);
});
}
else{
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
}
});
But, if we take a better look at your code, I do not understand why you want to use "each". You can achieve the same thing without it :
// Following code :
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
// Does the same thing as this one :
$(".authPermission").prop('disabled', true).prop('checked', false);
I refactored your code. Also enables the input field when the appropriate radio is clicked. This sould work:
function updateUI() {
var select = $("#authType");
var value = select.val();
var should_appear = (value.length == 0);
$("input:radio[name='authPermission']").attr('disabled',should_appear);
}
//binding...
$("input:radio").on("click", function() {
var should_display_textbox = !($(this).val() === "groupUser");
console.log(should_display_textbox);
$("input:text[name='authPermissionValue']").attr('disabled', should_display_textbox);
});
$("#authType").change(function(){
updateUI();
});
$(document).ready(function() {
updateUI(); //update also when page load
});
Something like this maybe?
$("#authType").change(function(){
var disabled = !$(this).val() ? true : false;
$("input:radio[name='authPermission']").each(function(){
$(this).prop('disabled', disabled );
$(this).prop('checked',false);
});
});
Related
I have a form that allows a user to create custom questions.
The user needs to insert the title for the question and then choose the type of the question.
If the type of question is radio button, checkbox or a select menu it should appear a div "availableOptions" that shows by default two input texts so the user can insert some option values.
Doubt:
When this "availableOptions" div appears there is also a button "add new option" that when is clicked it should appear another input text so the user can insert a new option value. Each option should also have always a remove button associated that when is clicked the user can remove that input text, but it should be always a minimum of one input text.
Do you know how to do this properly? I have the working example below but it's working neither the append nor the remove.
Example: https://jsfiddle.net/udx6pp8u/15/
HTML:
<form id="" method="post" class="clearfix" action="">
<div class="form-group">
<label for="inputName">Title</label>
<input type="text" class="form-control" id="inputName">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Type of Field</label>
<select class="form-control" id="customQuestionType">
<option>Text</option>
<option>Long text</option>
<option id="optionQuestion">Checkboxes</option>
<option id="optionQuestion">Radiobuttons</option>
<option id="optionQuestion">Select Menu </option>
</select>
</div>
<div class="form-group" id="availableOptions">
<label for="inputName">Available Options </label>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="option">
<input type="text" class="form-control">
<button id="removeOption">Remove Option</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-outline-primary mt-3" id="addNewOption">Add new Option</button>
</div>
</div>
<input type="submit" class="btn btn-primary float-right mt-3" value="Store"/>
</form>
CSS:
#availableOptions{display:none;}
jQuery:
var selected_option = $('#customQuestionType option:selected').attr('id');
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
if ($('#addNewOption').click(function() {
$('#availableOptions')
.append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
}));
if ($('#removeOption').click(function() {
$('#availableOptions') // how to remove the clicked otpion?
}));
}
Try this:
Note: Don't use id. Use class instead. One document should only have one unique id. Using multiple id="removeOption" will coz your script to behave incorrectly and also choose the first found and ignore the rest having the same id
$('#customQuestionType').change(function(){
var selected_option = $('option:selected', this).val();
if (selected_option == "optionQuestion") {
$('#availableOptions').show();
$('#addNewOption').click(function() {
$('#availableOptions').append('<div class="option"><input type="text" class="form-control"><button id="removeOption">Remove Option</button></div>');
});
}
});
$(document).on('click', '.removeOption', function(e) {
e.preventDefault();
$(this).closest('.option').remove();
})
DEMO:
https://jsfiddle.net/dL7opvak/21/
EDITED
I cannot find a perfect solution for this.
Is there a simple way to fadeIn the ".filter_on" div, if I click on a select option and/or radio button?
And by default, get this div to fade out again afterwards?
My fiddle
<div class="filter">
Filter <span class="filter_on">active</span>
</div>
<form>
<p>Vehicle?</p>
<select name="vehicle" size="2">
<option>Bike</option>
<option>Car</option>
</select>
</form>
<form>
<p>City?</p>
<input type="radio" id="all" name="city" value="All" checked>
<label for="all"> All</label></input>
<input type="radio" id="ny" name="city" value="New York">
<label for="ny"> New York</label></input>
<input type="radio" id="mh" name="city" value="Manhattan">
<label for="mh"> Manhattan</label></input>
</form>
You don't need to fadeOut since you cannot unselect from drop-down or cannot uncheck the radio button.
$('select, :radio').on('change', function() {
if ($('select option:selected').length === 0 && $(':radio:checked').val() === 'All') {
$('.filter_on').fadeOut();
} else {
$('.filter_on').fadeIn();
}
}).trigger('change');
trigger will execute this function automatically. Will fadeIn on the page load.
Demo: https://jsfiddle.net/tusharj/vyd7a2s8/1/
Demo -> http://jsfiddle.net/vyd7a2s8/4/
var defaultRadio = $(':radio:checked');
var defaultVehicle = $('[name=vehicle] option:selected');
$('[name=vehicle],[name=city]').on('change', function (e) {
var currentRadio = $(':radio:checked');
var currentVehicle = $('[name=vehicle] option:selected');
if (currentRadio[0].isEqualNode(defaultRadio[0]) && currentVehicle[0].isEqualNode(defaultVehicle[0])) {
$('.filter_on').fadeOut(500);
} else {
$('.filter_on').fadeIn(500);
}
});
Explanation - This will store the default selected values outside the function and uses them inside the click event to check the newly selected values.
What I want to do is get data from drop down and pass the data to textbox
here is my dropdown and textbox code
<select name="criteria_title" id="chosen_a" data-placeholder="Select Category" class="chzn_z span3 dropDownId chzn-done" style="display: none;">
<option value=""></option>
<option value="1" data-id="10">a</option>
<option value="2" data-id="20">b</option>
<option value="3" data-id="30">c</option>
<option value="4" data-id="40">d</option>
<option value="5" data-id="50">e</option>
</select>
<div class=" control-group formSep template">
<label for="input01" class="control-label">Category Rate*:</label>
<div class="controls">
<input id="title" name="criteria_rate" size="30" type="text" class="criteria_rate span2" value="" readonly="readonly" />
</div>
</div>
here is how to get data-id from dropdown
var criteria_id = $(this).attr('data-id');
here is how to pass data to textbox
$('.criteria_rate').val(criteria_id);
here is my dropdown screenshot
Any idea how to solve my problem?
Here is what you need (I think)
FIDDLE
$('#chosen_a').change(function() {
$('#title').val($('#chosen_a option:selected').data('id'));
})
This is the most simple way
$(document).ready(function () {
$("#chosen_a").change(function () {
$('#title').val($("#chosen_a").val());
});
});
Try this:-
$('#chosen_a').change(function(){
//get the selected option's data-id value using jquery `.data()`
var criteria_rate = $(':selected',this).data('id');
//populate the rate.
$('.criteria_rate').val(criteria_rate);
});
Fiddle
Refer .data()
Here is a possible solution, uses jquery but get the data through the event data instead of using jquery.data (notice that it is a few characters shorter doing it this way :P )
$("#chosen_a").on("change", function (evt) {
$("#title").val(evt.target.selectedOptions[0].dataset.id);
});
Demonstrated on jsfiddle
(gave an alternative as I misread the question initially, so now I'm a little late with my correction)
I made a dynamic form with an add button that creates a new division with the clone of the form but has a different ID. However, I also want to have a delete button with each division that removes the division that it is in, including the button itself.
I am familiar with JQuery .remove() method but I am having trouble selecting the division that the button is in.
<div id="attendees">
<div id="att1" class="attendee">
<form name="droplist" action="html_form_action.asp" method = "get">
<fieldset>
<legend><span class="legend">Filter</span></legend>
<label for="select">Category: </label>
<select id="select" size="1" >
<option value=" " selected="selected"> </option>
<option value="employees">Number of Employees</option>
<option value="hits">Hits on TechCrunch</option>
<option value="time_founded">Time Founded</option>
<option value="total_money">Total Money</option>
</select>
<div id='radioContainer' style="display:block;">
<input type="radio" id="condition" name="button" value="more"/> <label for="condition"> > </label></br>
<input type="radio" id="condition1" name="button" value="less"/> <label for="condition1"> < </label>
</div>
<div id='radioContainerTime' style="display:block;">
<input type="radio" id="condition2" name="button" value="later"/> <label for="condition"> After </label></br>
<input type="radio" id="condition3" name="button" value="earlier"/> <label for="condition1"> Before </label>
</div>
<div id = "text_box" style="display:block;">
<label for="input_value">Amount: </label>
<input type="text" id="box" name="input_value" value="textIn" />
</div>
<button>remove</button>
</fieldset>
</form>
</div>
Add more
</div>
My JavaScript so far is this:
$(function(){
var template = $('#attendees .attendee:first').clone(),
attendeesCount = 1;
var addAttendee = function(){
attendeesCount++;
var attendee = template.clone().find(':input').each(function(){
var newId = this.id.substring(0, this.id.length-1) + attendeesCount;
$(this).prev().attr('for', newId); // update label for (assume prev sib is label)
this.name = this.id = newId; // update id and name (assume the same)
}).end() // back to .attendee
.attr('id', 'att' + attendeesCount) // update attendee id
.prependTo('#attendees'); // add to container
};
$('.add').click(addAttendee); // attach event
});
$("button").click(function () {
$this.remove();
});
To delete the <div class="attendee"> that contains the button, you can just use this:
$("button").click(function () {
$(this).closest(".attendee").remove();
return(false);
});
This looks up the parent chain from the clicked button to find the first part with a class="attendee" and then removes that.
FYI, I'd strongly suggest putting a class on your delete button because it's a little dangerous to hook up to ALL buttons in your page.
To put a class on your delete button, change the HTML to this:
<button class="deleteButton">remove</button>
And, change the jQuery to this:
$(".deleteButton").click(function () {
$(this).closest(".attendee").remove();
return(false);
});
The return(false) prevents any default action in the form from occurring based on the click.
I have a form with a yes|no question displayed by radio selectors. I have two divs each one containing different drop downs based on the yes|no response. I cannot figure out how to show one and hide the other.
jsFiddle of this code
$(document).ready(function(){
$("input[name=radio_button]").change(function() {
var test1= $(this).val();
$("#"+test1).show();
$("div.test2").hide();
});
$("input[name=radio_button]").select(function() {
var test2= $(this).val();
$("#"+test2).show();
$("div.test1").hide();
});
});
<p>
<label class="required"> </label>
Yes <input name="radio_button" id="radio_button" type="radio" value="test2" onChange="" />
No <input name="radio_button" id="radio_button" type="radio" value="test1" />
</p>
<p>
<label class="required">Device: </label><br />
<div id="test1" class="test1_div">
<label style="font-weight:600;">test1</label>
<select name="order.item" id="item" >
<option value="default">Please Select item</option>
</select>
</div>
<div id="test2" class="test2_div">
<label style="font-weight:600;">item2</label>
<select name="order.item" id="device">
<option value="default">Please Select Device</option>
</select>
</div>
</p>
To make one hidden and other visible , you have to first hide both the blocks then add show() on the block you want to see. This will work for you.
Assuming your markup (html) is correct, try the following. It binds to click-events of those radio buttons (both of them), always hides both divs first, and then shows the appropiate div only (the one that belongs to the radio button clicked).
$(document).ready(function(){
$("input[name=radio_button]").click(function() {
var test= $(this).val();
$("div.test1, div.test2").hide(); //Hide both divs
$("#"+test).show();
});
});