I have a select box that looks like:
<select class="span12 select" data-placeholder="Wybierz operacje" tabindex="2" id="contract-operations">
<option></option>
<option value="1" data-url="<?php echo $aggregate_url; ?>" data-id="aggregate_invoice">
Wystaw fakturę dla zaznaczonych kontraktów
</option>
<option value="2" data-url="<?php echo $notification_url; ?>" data-id="">
Awizacja do klienta
</option>
<option value="3" data-url="<?php echo $notification_cost_url; ?>" data-id="">
Awizacja do klienta z potwierdzeniem
</option>
</select>
under it there is a link that attributes href and id are assigned dynamic and it looks like:
<a class="btn btn-info btn-large contract-operations" href="#">
<b class="icon-circle-arrow-up"></b>Wykonaj operacje dla zaznaczonych kontraktów
</a>
now depend on what option you choose from select box, id and href will change. Problem is with Id's, they are not working after attr assign any of them from js script that looks simple like:
select: function()
{
$.obj.$select.on('change', function(){
button.href = $(this).find(':selected').data('url');
var id = $(this).find(':selected').data('id');
$.obj.$a.attr('href', button.href);
$.obj.$a.attr('id', id);
});
}
They are assigning to a href element correctly but when I try to use those id's in another script or function it is like they never were assign.
use following
$(document).on('change','.select',function(){
var url = $(this).attr('data-url');
$('a.btn-info').attr({href:url});
});
working fiddle: http://jsfiddle.net/patelmilanb1/8H49X/2/
$(document).on('change', '.select', function (e) {
e.preventDefault();
var selectedURL = $(this).children('option:selected').data('url');
alert(selectedURL);
$('a.btn-info').prop('href', selectedURL);
});
Use on instead of delegate- it's been superseded.
$(document).on('change','.select', function()
{
$('a.btn-info').prop('href',$(this).attr('data-url'));
$('a.btn-info').prop('id',$(this).children('option[value="'+$(this).val()+'"]').prop('data-id')); });
});
What this does is bind the event "change" to the document instead of the ".select" elements. Then the 2nd argument is a selector which is what the event actually acts on. The 3rd is a typical event handler.
Rather than altering the element's id, which is generally static and unique, I would recommend adding another class instead. You can use .addClass, like so:
$(document).on('change','.select', function()
{
$('a.btn-info').addClass($(this).attr('data-id'));
});
Fiddle: http://jsfiddle.net/8H49X/6/
Related
I have a <select> tag with all options that are coming from the database. What I want to happen is when I select on a particular option, I want to get class name, but I am getting Undefined when I do it this way. Why is this happening?
HTML:
<select id="mySelect" class="form-control get-this">
<?php
foreach ($res as $r) {
?>
<option class="<?= $r->item_name ?>" ><?= $r->item_name ?></option>
<?php }
?>
</select>
JavaScript:
<script>
$('.get-this').on('change', function() {
var optionSelected = $("option:selected", this);
var valueSelected = $('option:selected').attr('class');
alert($(this).find('option:selected').attr("class"));
});
</script>
To get the class name of an element, use JavaScript's .className property.
Syntax:
object.className
Example:
console.log(document.querySelector("#element").className);
For multiple classes, use classList (only in newer versions):
// Gets fourth class
console.log(document.querySelector("#element").classList[3];
To emulate classList in older versions, use .split(/\s+/)
// Gets fourth class
console.log(document.querySelector("#element").className.split(/\+s/)[3];
Source: How to get class of clicked element
Edit:
#Andreas was right. The code you have already works and it dosen't need to be modified.
console.log($("#element").attr("class"));
$("#js").text(document.querySelector("#element").className);
$("#jq").text($("#element").attr("class"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element" class="my-class"></div>
<code>.className</code> returns: <span id="js"></span><br>
<code>.attr("class")</code> returns: <span id="jq"></span>
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
I've got the follwoing HTML structure (I do not have the IDs of the following elements because they are dynamically created):
<fieldset>
<div class="classA">
<select onchange="updateInputBox()">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</selects>
</div>
<div class="classB">
<input data-myAttribute="case1">
</div>
<div class="classC">
<a type="button">
<i class="fa fa-remove">x</i>
</a>
</div>
</fieldset>
The filedset and it's children is dynamically created. I want to change the attribute in the inputBox depending on what the user selected in the selectBox.
Here is an example how I would have done if the element fieldset would not have been dynamic (the following contains elements have IDs, but only because I want to demonstrate what I want; in reality I don't have IDs because they are dynamically created by clicking a button, that I do not show here):
https://jsfiddle.net/thadeuszlay/6bsgazvv/4/
But unfortunately I don't have the id of the fieldset, because it is dynamically created. Is there a way how you can get the position of the current element?
I tried to pass itself in the updateInputBox-function:
<select id="selectBox" onchange="updateInputBox('+ this +')">
I also tried with jQuery:
$(this).parent().parent()
but in both cases the console would say
"Unexpected identifier"
Update:
Inside the function doing something like this (currentElement is the selectBox/DropDownBox):
currentElement.parent().parent().setAttribute("data-myAttribute", "hello");
Uncaught TypeError: selectBox.parent is not a function
You can use jquery 'closest' for this as below.
HTML
<select id="selectBox" onchange="updateInputBox(this)">
JS
function updateInputBox(selectElm) {
var inputElm = $(selectElm).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(selectElm).val());
}
// instead of inline onchange event and the above code, you can use the below to trigger the event
$(document).on('change', 'fieldset select', function () {
var inputElm = $(this).closest('fieldset').find('input');
inputElm.attr('data-myAttribute', $(this).val());
});
In updateInputBox, simply look at the selectedIndex of #selectBox
<select id="selectBox" onchange="updateInputBox(this)">
function
function updateInputBox(dropdowntBox) {
var inputBoxField = document.getElementById("inputBox").setAttribute("data-myAttribute", dropdowntBox.value);
}
Here is jquery version:solution
You need to trigger change() event for select with ID selectBox
$(document).on('change','select',function(){
var value=$(this).val();
$(this).parents('fieldset').find('input').attr('data-myAttribute',value);
});
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
I've got the following code which basically when the value of the select is changed I want to be able to take the new value and add it to the already existing value (or minus it).
I'm having an issue actually grabbing the value. I have this to create the select lists:
<li class="extraHeight">
<asp:Image runat="server" CssClass="iconImageMove" ID="Image14" ImageUrl="~/images/icons/carpark_off.png" />
<div class="flipWidth">
<select name="access" class="change" id="carpark_off" runat="server">
<option value="0">Off</option>
<option value="256">On</option>
</select>
</div> <br /> <p class="noWrap">Accessible Car parking facilities</p>
</li>
<li class="extraHeight">
<asp:Image runat="server" CssClass="iconImageMove" ID="Image15" ImageUrl="~/images/icons/parking_off.png" />
<div class="flipWidth">
<select name="access" class="change" id="parking_off" runat="server">
<option value="0">Off</option>
<option value="33554432">On</option>
</select>
</div> <br /> <p class="noWrap">Customer Car parking facilities</p>
</li>
<li class="extraHeight">
<asp:Image runat="server" CssClass="iconImageMove" ID="Image16" ImageUrl="~/images/icons/staff_off.png" />
<div class="flipWidth">
<select name="access" class="change" id="staff_off" runat="server">
<option value="0">Off</option>
<option value="8192">On</option>
</select>
(There are a lot more but that gives you an idea)
I'm using the following jQuery to detect the change and try and grab the value but it's not working:
<script>
var value = $("select").val()
$("select").change(function () {
alert(value);
})
</script>
Any suggestions would really be appreciated!
Tom
You are only selecting the initial value. You need to get the value inside the change event.
$("select").change(function () {
var value = $(this).val()
alert(value);
})
You set your value before the change try this:
<script>
$("select").change(function () {
var value = $(this).val()
alert(value);
})
</script>
Calling var value = $("select").val() will save the value of the first <select> element matched by the selector into a variable as it was when that code was run - it won't update when you change the value of that element.
Instead, what you can do is use this inside your change() callback function to refer to the <select> element that has changed, and get its value, like this:
$("select").change(function () {
alert(this.value);
});
You would do something like this:
$("select").change(function () {
alert($(this).val());
})
You are only getting the value out once and then just displaying the same thing on the change event.
See working demo : http://jsfiddle.net/JsKeS/
First of all wrap your script in $(document).ready(), so that it will be executed after the page loaded. Secondly get the value of select inside the callback:
$(document).ready(function(){
var value = $("select").val()
$("select").change(function () {
alert($(this).val());
});
})
Try:
<script>
$(document).ready(function () {
$("select").change(function () {
var value = $(this).val();
alert(value);
});
});
</script>
which will attach your change handler to the select elements after the DOM has loaded them.
Also, the value should be scoped in the handler, or the value will not necessarily be updated when other select elements fire the change event.