HTML <select> JQuery .change not working - javascript

Alright I don't see why this isnt working. It seems pretty simple.
Here is my drop-down menu:
<div>
<form>
<select id='yearDropdown'>
<c:forEach var="years" items="${parkYears}">
<option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option>
</c:forEach>
</select>
</form>
</div>
and here is the JavaScript
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});
Right now I just want to get it working so I can add functionality. Thanks!

That code is syntactically correct. Most likely running it at the wrong time.
You'll want to bind the event when the DOM is ready:
Native JS/DOM
window.addEventListener('DOMContentLoaded', () => {
const yearDropDown = document.getElementById('yearDropdown');
yearDropDown.addEventListener('change', () => {
alert(yearDropDown.value)
});
});
jQuery
$(function(){ /* DOM ready */
$("#yearDropdown").change(function() {
alert('The option with value ' + $(this).val());
});
});
Or, use live:
$("#yearDropdown").live('change', function() {
alert('The option with value ' + $(this).val());
});
Or, use delegate:
$(document.body).delegate('#yearDropdown', 'change', function() {
alert('The option with value ' + $(this).val());
});
Or, if you're using jQuery 1.7+:
$("#yearDropdown").on('change', function() {
alert('The option with value ' + $(this).val());
});
Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.

I have tried your code in jsFiffle.
I manually added some years as options.
It works right.
Just bind the .change event in the $(document).ready:
$(document).ready(function(){
$("#yearDropdown").change(function () {
alert('The option with value ' + $(this).val());
});​
});

Your code is correct and is working for me, see here: http://jsfiddle.net/mobweb/2Skp9/
Are you sure jQuery has been loaded properly?

Not sure if this will help, but you could try this:
$("#yearDropdown").live("change", function () {
alert('The option with value ' + $(this).val());
});

Related

Checkbox trigger change event

I am verifying certain data then I am dynamically checking checkbox and I want to trigger change event of checkbox.
$("#chk").prop("checked", true).trigger("change");
Change event
$("#chk").change(function () {
if ($(this).is(':checked')) {
if (localStorage.getItem('A') == undefined && sessionStorage.getItem('A') == null) {
location.href = "/" + lang.split('-')[0] + "/login.aspx";
}
$("#dvClass").hide();
$("#dvPromoCode").hide();
$("#resultby").empty();
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
else {
$("#dvClass").show();
$("#dvPromoCode").show();
$("#resultby").empty();
$("#resultby").append('<option value="AirAvailability">' + Res.schedule + '</option>');
$("#resultby").append('<option selected value="Flex">' + Res.flexidates + '</option>');
}
});
but it is not triggering the change event. But same if I execute from console than it works as expected. I want to know what can be issue.
The order of the function is important here.
You have place your change event before setting the checkbox values. Look at the below code.
$("#chk").prop("checked", "checked").trigger("change");
$("#chk").change(function() {
alert("triggered!");
});
The above won't work because when the jquery run for first line, it doesn't have any change event for the checkbox. You can check the same in this Fiddle
Now place your change event function before calling it like below.
$("#chk").change(function() {
alert("triggered!");
});
$("#chk").prop("checked", "checked").trigger("change");
Now you can get the expected result. You can check the same in this Fiddle
Always better to use the on event for the dynamic added elements like below.
$("#chk").on('change', function() {
alert("triggered!");
});
Be you sur you declared the change event before the prop change instr ; see updated answer :
$(function(){
$("#chk").on("change", function() {
console.log(this.checked)
});
$("#chk").prop("checked", true).trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="chk" type="checkbox" />

How do I remove an input field after it's being emptied

I am adding input fields on keystroke, by using an example from the answer for this question. This is my example. I was trying in various ways to remove field if user deletes content from it, so that there are always fields that have some content and one last empty field for adding more, but I just can't find a solution.
This is the code:
$(document.body).on("input", ".external-media-input:last", function () {
var inputID = (parseInt($(this).attr('id')) + 1);
$(".input_fields_wrap").append('<div><input class="external-media-input" id="' + inputID + '" name="external_media[]" type="text"/></div>');
});
You can use on('blur') or .on('focusout')
//...
.on('blur', ".external-media-input:not(:last)", function () {
if(!$(this).val()) $(this).remove();
});
JSFiddle
You can use also on('keyup')
$(document.body).on("keyup", ".external-media-input", function(){
if($(this).val() == '')
$(this).remove();
});
here is your fiddle: https://jsfiddle.net/bembvptx/2/
In your style add one more event:
$(document.body).on("input", ".external-media-input", function () {
if (!$(this).val())
{
$(this).remove();
}
});

Attempting to loop and print an element in jQuery

I am attempting to loop through a dynamic element and then print it with jquery,
Heres the code i use
$('.recipe-steps #addNewStep').on('click', function () {
var s = $('.recipe-steps .step').size() + 1;
$('<div class="step pure-u-1-1"><textarea id="step" name="step_detail[]" class="pure-u-1" placeholder="Step ' + s + '"></textarea>×</div>').appendTo($('.recipe-steps .steps'));
return false;
});
$(document).on('click', '.step .remove', function () {
$(this).parents('.step').remove();
return false;
});
however its only printing out the first element and not the preceding ones. I have created a fiddle can anyone see why?
http://jsfiddle.net/drk8X/
I wasn't able to come up with the perfect solution (will have a look later) but I have redesigned the function to work to an extent.
$("body").on('input propertychange', function () {
var outputme="";
$('textarea').each(function (index) {
outputme+='<br>'+(index+1) + '. ' + $(this).val();
});
$('#lp-step').html('<h3>Method</h3>'+outputme);
});
This will update the "preview" on change of the text area, use CSS Selectors to narrow down the scope, but id reccomend you looking at your HTML and try and simplify it a bit more.
http://jsfiddle.net/drk8X/2/

jQuery Toggle not working using this.name

I've created a contact form with validation and was trying to bolt on a help function whereby someone clicks on the question mark and a div with the explanation pops up.
I found a way to do it using a variable and "this" selector which seemed to work fine but it's stopped working and I can't seem to prevent the default # behaviour.
Having looked at similar questions, nothing has indicated what the problem might be. Here is the function:
$(function() {
//show/hide
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= this.name;
$("#"+divname).toggle();
return false;
});
});
jsFiddle link:http://jsfiddle.net/dvmac/dpVzL/2/
The # selector selects based off of id. If you want to select off of name, you need the attribute slector: '[name="' + divname + '"]'
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= this.name;
$('[name="' + divname + '"]').toggle();
return false;
});
An even better way is to just to do this: $(this)
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
$(this).toggle();
return false;
});
And if you have dynamically created elements, then you may want to try this:
$(document).on('click', 'a.form-question-help-link', function(e) {
$(this).toggle();
e.preventDefault();
});
use $(this).attr('name') or $(this).prop('name').
Check this fiddle.
should be $(this) instead of this
$(function() {
//show/hide
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= $(this).name;
$("#"+divname).toggle();
return false;
});
});

.click() in a <div> in a <div> does not work

$('#A').click(function () {
$('#A1').prepend('<div class="AcL" id=' + i + '>Hello<span class="RmMe" id="' + i + '" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').click(function () {
alert("OK");
});
<div id="A1"></div>
Any idea why the click is not working?
You need to use .delegate() or .live() because you are attempting to bind a handler to an element that does not yet exist.
$('#A').click(function() {
$('#A1').prepend('<div class="AcL" id='+i+'>Hello<span class="RmMe" id="'+i+'" style="margin-left:20px; cursor:pointer;">X</span></div>');
i++;
});
$('.RmMe').live('click', function() { alert( 'OK' ); });
Try that.
EDIT:
However, should you be using jQuery 1.7+, the .on method is the preferred approach: See post from xdazz
$('.RmMe').on('click', function () {
alert("OK");
});
Good luck!
Try use .onDoc.
$('.RmMe').on('click', function () {
alert("OK");
});
You have to use
$('.RmMe').on("click",function(){
alert("OK");
});
because this element does not exist when your DOM is created, it is inserted afterwards and you cannot bind click to the element which does not exist. .live adds an event listener for you, which makes it easy to achieve the task you want.

Categories

Resources