I need to check if the element targeted is first element in its class and perform actions accordingly.
For eg. I have a select element with class name 'team'.
Now I need to check if the selected element is whether a first element or not.
Here's my HTML:
Initially there's a single select and checkbox input. On clicking a button, more select and checkbox inputs are added.
<div class="col-sm-7" id="include-fields">
<select name="team[]" class="form-control team" id="team">
<option></option>
<option value="1">1</option>
</select>
<label>Lead</label>
<input type="checkbox" name="lead_check[]">
</div>
<div class="col-sm-offset-2">
<button id="includes" class="btn btn-success"><i class="fa fa-plus"></i>
</button>
</div>
Dynamic select and checkbox generating:
$('#includes').click(function(e)
{
e.preventDefault();
$('#include-fields').append('<div class="holder-includes"><i class="fa fa-trash-o pull-right"></i>' +
'<select name="team[]" class="form-control team">'+
'<input type="checkbox" name="lead_check[]"></div>');
var items = "";
$.post("teamFetch", function(data)
{
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.title+"</option>";
});
$(".team:last").html(items);
}, "json");
});
I tried following, but no luck:
$(document).on("change",".team",function(e){
var target = $(e.target);
if(target.is(".team:first"))
{
$(this).parent('div#include-fields').find("input[name='lead_check[]']").val($(this).val());
}
$(this).siblings("input[name='lead_check[]']").val($(this).val());
});
Here, first select element is already there, but other select elements are added dynamically later. They all have the same class team.
To check if the select element is a first child of its parent among all the sibling you can use this script.
$(document).ready(function(){
$(document).on("change","#include-fields .team:first",function(){
alert($(this).val());
});
});
Alert will only get triggered on the first select element. Here is a fiddle
Related
How to prevent an input element (text, text area, select, radio button, checkbox) from getting focus?
I basically want to make them disabled without changing disabled or readonly attribute but denying them focus.
Is there a neat way to scan the DOM using certain search criteria and apply that to the search result?
Say I want to find all input that are not tagged with a certain css class and make them un-selectable!
Give the elements that should be allowed focus the focus class. Then use a focus event handler that unfocuses the element.
$(document).on("focus", ":input:not(.focus)", function() {
$(this).blur();
console.log("Focus blocked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox"> No focus<br>
<input type="checkbox" class="focus"> Focus
This uses event delegation so you can add and remove the focus class dynamically.
I am not sure if I got what you mean but can you please run this:
$('#disabler').change(function() {
resetFields();
var this_value = $(this).val();
if(this_value != 'none'){
$('.'+this_value).attr('disabled', true);
}
});
$('.disabler').click(function(){
resetFields();
var this_value = $(this).attr('id');
$('.'+this_value).attr('disabled', true);
});
$('#reset').click(function(){
resetFields();
});
function resetFields()
{
$('.first, .second').removeAttr('disabled');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="first" value="A"><br/>
<select class="first"><option value="1">A</option></select><br/>
<textarea class="first" col="2" row="10">A</textarea><br/>
<br/><br/>
<input class="second" value="B"><br/>
<select class="second"><option value="1">B</option></select><br/>
<textarea class="second" col="2" row="10">B</textarea><br/>
<br/><br/>
<select id="disabler">
<option value="none">-select-</option>
<option value="first">Disable first</option>
<option value="second">Disable second</option>
</select><br/>
<button id="first" class="disabler">Disable first only</button><br/>
<button id="second" class="disabler">Disable second only</button><br/>
<button id="reset">Reset</button>
Hello Everyone I want to capture price from this span using jquery how can i achieve this please suggest something
<span class="amount"><i class="fa fa-inr"></i>1,000</span>
DropDown:
<li class="tmcp-field-wrap">
<label for="tmcp_select_1">Select</label>
<select class="tmcp-field support-layer-firmness tm-epo-field tmcp-select tm-valid" name="tmcp_select_0">
<option value="Select Firmness_0" class="tc-multiple-option tc-select-option" data-price="">Select Firmness</option>
<option value="Soft_1" class="tc-multiple-option tc-select-option" data-price="1000">Soft</option>
<option value="Medium_2" class="tc-multiple-option tc-select-option" data-price="1500">Medium</option>
<option value="Hard_3" class="tc-multiple-option tc-select-option" data-price="2000">Hard</option>
</select>
<span class="price tc-price hidden">
<span class="amount"><i class="fa fa-inr"></i>1,000</span>
</span>
Now i want to get value using onchange event
I have tried so far
$(".support-layer-firmness .tc-price span").on("change", function() {
var price = $('span.amount').text();
alert(price);
});
You can capture the text by using jquery Class Selector
$('span.amount').text(); // output 1,000
Class Selector: Selects all elements with the given class. Reference
As per comment if you want to get the same span value onChange event then try this.
Method 1
$('select').on('change', function() {
$('span.amount').text();
});
Method 2
You can use also class for selecting the select element
$('select.tmcp-field').on('change', function() {
$('span.amount').text();
});
use jquery selector using class name
$(".amount").text();
https://jsfiddle.net/mc7h22f7/
Please check this demo
You can easily get span value as follow.
On Change you can do something like this
$('.tmcp-select').on('change', function (e) {
alert($('span.amount').text());
});
OnChange Example
Im having trouble having code onchange inside onchange event.
some works and some dont work due to that.
<script>
$(document).on('change', '.sellkop', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#text_container").after(price_option());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").css({"display": 'none'
});
};
});
$('#category_group').on('change', function() { // this is select options
if ($(this).val() == 101) {
$("#underKategory").css({"display": 'none'});
$("#modelcontainer").remove();
$(".toolimage").css({ "display": 'block'});
$('.sellkop').on('change', function() { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").css({"display": 'block'});
$(".toolimage").css({"display": 'block' });
} else {
$(".toolimage").css({"display": 'none'});
}
});
} else {
$(".bilar").remove();
$(".toolimage").css({ "display": 'none'});
}
if ($(this).val() == 102) {
$(".houses_container").remove();
$(".toolimage").css({"display": 'none'});
$("#underKategory").css({"display": 'inline-block'});
$("#modelcontainer").remove();
}
///............many other values continue
});
</script>
i know there is better way to manage this code and simplify it , how can i do it ?
EDIT:
what i want is : if i select an option , then get values to that option, then under this category option there is radio buttons , then every check button i need to get some data displayed or removed
here is a fiddle there looks my problem by jumping from categories when i select buy or sell , so
if i select category-->check buy -->then select others . i dont get same result as if i select directly cars ---> buy
I have never resorted to even two answers before (let alone three), but based on all the comments, and in a desire to keep things simple another solution is to data-drive the visibility of other items based on selections, using data- attributes to store the selectors on the options and radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/28/
e.g the HTML for the select becomes
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101' data-show="#sellbuy,.cars,.toolimage,#licenscontainer">cars</option>
<option value='102' id='cat102' data-show="#sellbuy,#underKategory">others</option>
</select>
and the radio buttons like this:
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' data-show="#price_container,.cars,.toolimage"/>
The code becomes very simple then, simply applying the filters specified in the selected items.
$(document).on('change', '.sellkop', function () { // this is radio button
// Hide defaults
$("#price_container,.cars,.toolimage").hide();
// Show the items desired by the selected radio button
$($(this).data("show")).show();
});
$('#category_group').on('change', function () { // this is select options
// Get the various possible data options and decide what to show/hide based on those
var $this = $(this);
var value = $this.val();
// Get the selected option
var $li = $('option[value='+ value+']', $this);
// Hide all the defaults first
$('#licenscontainer,.cars,.toolimage,.sell,#underKategory').hide();
// Now show any desired elements
$($li.data('show')).show();
// Fire change event on the radio buttons to ensure they change
$('.sellkop:checked').trigger('change');
});
This is a very generic solution that will allow very complex forms to turn on/off other elements as required. You can add data-hide attributes and do something similar for those too if required.
Note: This was an attempt to fix the existing style of coding. I have posted an alternate answer showing a far simpler method using hide/show only.
A few problems.
If you must nest handlers, simply turn them off before you turn them on. Otherwise you are adding them more than once and all the previously recorded ones will fire as well.
Your HTML strings are invalid (missing closing </div>)
You can simply use hide() and show() instead of all the css settings. You should use css styling for any specific element styling requirements (e.g. based on classes).
You need to replace specific divs, rather than keep using after, or you progressively add more html. For now I have use html to replace the content of the #text_container div.
HTML in strings is a maintenance nightmare (as your example with missing </div> shows). Instead use templates to avoid the editing problems. I use dummy script blocks with type="text/template" to avoid the sort of problems you have found. That type means the browser simply ignores the templates.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/17/
HTML (with templates)
<script id="saljkop">
<div class='sex sell' id='sellbuy' >
<label ><input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked'/> Sell </label>
<label ><input id='rk' type='radio' class='radio sellkop' value='k' name='type'/>buy</label>
</div>
</script>
<script id="price_option">
<div class="container" id = "price_container">
<div>
<label><input class="price_option" name="price_opt" value="1" type="radio"/> Fix </label>
<label class="css-label"><input class="price_option" name="price_opt" value="2" type="radio"/> offer </label>
</div>
</div>
</script>
<script id="cars">
<div class="cars" >
<div id="licenscontainer" ><div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</script>
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">textttttt</div>
New jQuery code:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#sellbuy").after($('#cars').html());
$("#text_container").html($('#price_option').html());
$("#underKategory").hide();
$(".toolimage").show();
$('.sellkop').off('change').on('change', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#licensenumber_c").show();
$(".toolimage").show();
} else {
$(".toolimage").hide();
}
});
} else {
$(".cars").remove();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").remove();
$("#categories").after($('#saljkop').html());
$("#text_container").html($('#price_option').html());
$(".toolimage").hide();
$("#underKategory").show();
}
///............many other values continue
});
Now if you prefer to not nest handlers (recommended), just add to your existing delegated event handler for the radio buttons:
$(document).on('change', '.sellkop', function () { // this is radio button
console.log('.sellkop change');
if ($("#rs").is(':checked')) {
$("#text_container").html($('#price_option').html());
$("#licensenumber_c").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").remove();
$("#licensenumber_c").hide();
$(".toolimage").hide();
};
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/20/
Note: This was a second answer, hoping to simplify the overall problem to one of hiding/showing existing elements. I have posted a third(!) answer that takes it to an even simpler scenario using data- attributes to provide the filter selections.
I am adding a second answer as this is a complete re-write. The other answer tried to fix the existing way of adding elements dynamically. I now think that was simply a bad approach.
The basic principal with this one is to have very simple HTML with the required elements all present and simply hide/show the ones you need/ Then the selected values are retained:
This uses the multi-structure to effectively hide.show the licence field based on two separate conditions.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/4s5rwce2/23/
Html (all element s present, just the ones you do not need hidden):
<div id="categories">
<select name="category_group" id="category_group">
<option value="0">choose category</option>
<option value='101' id='cat101'>cars</option>
<option value='102' id='cat102'>others</option>
</select>
<div class='sex sell' id='sellbuy' style="display: none">
<label>
<input id='rs' type='radio' class='radio sellkop' value='s' name='type' checked='checked' />Sell</label>
<label>
<input id='rk' type='radio' class='radio sellkop' value='k' name='type' />buy</label>
</div>
<div class="cars" style="display: none">
<div id="licenscontainer">
<div id="licensenumber_c">
<input id="licensenumber" placeholder="Registrer number" type="text" value="" />
</div>
</div>
</div>
</div>
<div id="underKategory">sthis is subcategory</div>
<div id="toolimage1" class="toolimage">dddddd</div>
<div id="text_container" class="text_container">
<div class="container" id="price_container" style="display: none">
<div>
<label>
<input class="price_option" name="price_opt" value="1" type="radio" />Fix</label>
<label class="css-label">
<input class="price_option" name="price_opt" value="2" type="radio" />offer</label>
</div>
</div>
</div>
jQuery:
$(document).on('change', '.sellkop', function () { // this is radio button
if ($("#rs").is(':checked')) {
$("#price_container").show();
$(".cars").show();
$(".toolimage").show();
};
if ($("#rk").is(':checked')) {
$("#price_container").hide();
$(".cars").hide();
$(".toolimage").hide();
};
});
$('#category_group').on('change', function () { // this is select options
if ($(this).val() == 101) {
$(".sell").hide();
$("#sellbuy").show();
$(".cars").show();
$("#underKategory").hide();
$(".toolimage").show();
$('#licenscontainer').show();
} else {
$('#licenscontainer').hide();
$(".cars").hide();
$(".toolimage").hide();
}
if ($(this).val() == 102) {
$(".sell").hide();
$("#sellbuy").show();
$(".toolimage").hide();
$("#underKategory").show();
$(".cars").hide();
}
$("#price_container").toggle($("#rs").is(':checked'));
///............many other values continue
});
The following contain dynamic values
<c:forEach items="${allUserList}" var="eachUser">
<span class="name"> ${eachUser.getUserName()} <span>
<select class="role">
<c:forEach items="${roleList}" var="eachRole">
<option value="${eachRole.getRoleName()}">${eachRole.getRoleName()}</option>
</c:forEach>
</select>
<input type="button" class="add" value="add" />
</c:forEach>
When i click on add button i should see corresponding name, selected role in a alert box (e.g {jack, admin})
How to do this??
Using the class attribute of the button as a selector, you can use the .prev function to find the <select> element preceding the button:
$(".add").on("click", function() {
alert($(this).prev(".role").val()); // Role
alert($(this).prevAll(".name").text()); // Name
});
You don't need event delegation in this instance, as JSP will generate this code before it reaches the client.
I want to find a closest class of the given object. My markup looks like this:
<div class="table_settings">
<div style="float:left;">
<div class="stats_options" id="yearSelector" style="width:140px;">
<div style="float:left"><span class="optionValue"></span></div>
<div style="float:right; margin-top:11px;"><img src="../images/arrow_down.png" /></div>
<div class="clear"></div>
</div>
<div id="yearSelectorOptions" class="option_list" style="width:160px; display:none; margin-top:0px;">
<ul>
<li><input type="radio" name="year" value="2" style="display:none;" alt="Winst en verlies" checked="checked" />Winst en verlies</li>
<li><input type="radio" name="year" value="1" style="display:none;" alt="Eindbalans" />Eindbalans</li>
</ul>
</div>
</div></div>
The jquery looks like this:
$(".option_list ul li").click(function()
{
$(this).children('form input[type="radio"]').prop('checked', true);
value = $(this).children('input[type="radio"]:checked').attr('alt');
$(this).parents('.table_settings').children('.optionValue').text(value); }
What I want is when I click on the [li] that the value of the clicked [li] gets into the class optionValue.
I want to duplicate this list so it have to work for more lists on one page.
I hope someone can help me.
Thanks in advance!
//select all the `<li>` elements that are the children of the `<ul>` element that is the child of the `.options_list` element
$(".option_list").children('ul').children().click(function() {
//select the first ancestor element with the `.table_settings` class,
//then select the `.optionValue` element that is a descendant of the `.table_settings` element,
//then set it's text to that of the input element inside the `<li>` element clicked
$(this).closest('.table_settings').find('.optionValue').text($(this).children().val());
});
Here is a demo: http://jsfiddle.net/rpVxV/
Try this:
$('.option_list')
.find('li')
.click(function () {
var $radio = $(this).children(':radio'),
value = $radio.attr('alt'), // Or `$(this).text()` ...
$(this)
.parents('.table_settings')
.find('.optionValue')
.text(value);
});
Your code is basically not working because of this line:
//`.optionValue` is not IMMEDIATE
// children of `.table_settings`
// so it won't work
$(this).parents('.table_settings').children('.optionValue').text(value); }