Why jquery "change" event does not work in my example? - javascript

When a [name="tip"] has the first value, display a specific element, otherwise it would display another element.
Both elements have the display:none property. When I load the page I check the select value and fadeIn the desired element automatically.
Everything works fine except when I try to change the selected option: nothing happens. I added both javascript onchange to that item and jquery .change() and nothing happens. Can you tell me why it does not work in my example?
<form id="fm-account-properties-tab" method="POST">
<table width="300px" style="margin-top:10px;" align="center" >
<tr>
<td align="left">
<select class="easyui-combobox" name="tip" style="width:200px;" class="easyui-validatebox" required="true" onchange="changeType();">
<option value="l1">l1</option>
<option value="l2">l2</option>
<script>
$(document).ready(function(){
$('[name="tip"]').val('<?php echo $a['tip'];?>');
});
</script>
</select>
</td>
</tr>
<tr id="l1" style="display:none">
<td align="left">
<select class="easyui-combobox" name="l1" style="width:200px;" class="easyui-validatebox" required="true">
</select>
</td>
</tr>
<tr id="l2" style="display:none">
<td align="left">
<select class="easyui-combobox" name="l2" style="width:200px;" class="easyui-validatebox">
</select>
</td>
</tr>
</table>
</form>
<script>
function changeType()
{
if($('[name="tip"]').val()=='l1')
{
$('#l1').fadeIn();
$('#l2').hide();
}
else
{
$('#l2').fadeIn();
$('#l1').hide();
}
}
$(document).ready( function () {
changeType();
$('[name="tip"]').change(function(){ alert('1');});//it never alerts me
});

use .on for newer jQuery versions (jQuery > 1.7.x reference)
function changeType() {
if ($('[name="tip"]').val() == '___') {
$('#1').fadeIn();
$('#2').hide();
} else {
$('#2').fadeIn();
$('#1').hide();
}
}
$(document).ready(function () {
changeType();
$('select[name="tip"]').on('change', function() {
changeType();
});
});
you have a double class attribute on your select.
here is a working sample http://jsfiddle.net/tvhKH/

May be you should use js error event to figure out the error in that code. E.g, <script> try
{....all your codes here...}
catch(err)
{alert("THE ERRor" + err.message);} </script>. These code will alert your error and the exact point it occurs. Good luck!

First, you should try to add a
console.log("It works");
or a
alert("It works")
in your method so you know if it is actualy called.
Then I think the issue may come from FadeIn() only works on elements with css {display: none} and visibility different of 'hidden', so are you sure your elements are ? In doubt, you may replace
.fadeIn();
by
.css('visibility','visible').hide().fadeIn(); // hide() does the same as display: none
Then please let me know if you have more information after doing that.

Related

JS w/ Kendo: Change label text on dropdown selection change

I'm attempting to change an Input label in my cshtml file by using my JS script, when any drop down selection is made. I've followed the documentation - but I'm not getting the intended result. There are no compile or runtime errors - and I have cut out anything that I didn't think was necessary for you all to see. Please let me know if I've left something out.
HTML:
<input id="searchByInput" class="rptInputBxWidth" data-role="dropdownlist" data-text-field="Value" data-value-field="Key" data-bind="value:searchBys_Value, enabled:searchBys_Enabled, source:searchBys_Source " data-option-label="SELECT" data-auto-bind="false" data-value-primitive="true" />
<td id="entryFieldInputLabel" class="inputLabel" align="right">123456</td>
JS:
$(document).ready(function () {
$('#searchByInput').change(searchByDropDownSelectionChange)
})
function searchByDropDownSelectionChange() {
$('#entryFieldInputLabel').text('Changed')
}
I've removed the many table row tags, and the data source loads correctly as well. What I expect to happen is that when the drop down (#searchByInput) is changed, the text on the label (#entryFieldInputLabel) is changed to "Changed"
Use html selector instead of text (td has no text proprety ):
$(document).ready(function () {
$('#searchByInput').change(searchByDropDownSelectionChange)
})
function searchByDropDownSelectionChange() {
$('#entryFieldInputLabel').html('Changed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="searchByInput" class="rptInputBxWidth" data-role="dropdownlist" data-text-field="Value" data-value-field="Key" data-bind="value:searchBys_Value, enabled:searchBys_Enabled, source:searchBys_Source " data-option-label="SELECT" data-auto-bind="false" data-value-primitive="true" />
<table>
<tr><td id="entryFieldInputLabel" class="inputLabel" align="right">1234</td>
</tr>
</table>
It would be better if you use span inside your table td
$(document).ready(function () {
$('#searchByInput').change(searchByDropDownSelectionChange)
})
function searchByDropDownSelectionChange() {
$('#entryFieldInputLabel span').html('Changed')
}
/*
or simply
$('#searchByInput').change(function(){
$('#entryFieldInputLabel').html('Changed');
})
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="searchByInput" class="rptInputBxWidth" data-role="dropdownlist" data-text-field="Value" data-value-field="Key" data-bind="value:searchBys_Value, enabled:searchBys_Enabled, source:searchBys_Source " data-option-label="SELECT" data-auto-bind="false" data-value-primitive="true" />
<table>
<tr><td id="entryFieldInputLabel" class="inputLabel" align="right"><span>123</span></td>
</tr>
</table>
You just need to add <table> Markup so jQuery can select your <td> tag ID
<table>
<tr>
<td id=""></td>
</tr>
</table>
$(document).ready(function () {
$('#searchByInput').change(searchByDropDownSelectionChange);
function searchByDropDownSelectionChange() {
$('#entryFieldInputLabel').text('Changed!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchByInput" class="rptInputBxWidth" data-role="dropdownlist" data-text-field="Value" data-value-field="Key" data-bind="value:searchBys_Value, enabled:searchBys_Enabled, source:searchBys_Source " data-option-label="SELECT" data-auto-bind="false" data-value-primitive="true" />
<table>
<tr>
<td id="entryFieldInputLabel" class="inputLabel" align="right">123456</td>
</tr>
</table>
This issue is resolved, and can be closed. The solutions offered both reaffirmed that the issue was not in the code I provided. After experimentation, the solution was found in the order in which the "change" call was made in the JS ready function.
This particular call needed to be made after the page specific HTML was loaded, but before the kendo data was bound by ID.

How to iterate js function?

I have some repeat button control functions as below, is there a way to iterate them and reduce amount of code?
$('[id$=cBC1]').change(function () {
if ($(this).is(':checked')) {
$(".cBC1_Row").prop("disabled", true);
}
else {
$(".cBC1_Row").prop("disabled", false);
}
$('select').material_select();
});
$('[id$=cBC2]').change(function () {
if ($(this).is(':checked')) {
$(".cBC2_Row").prop("disabled", true);
}
else {
$(".cBC2_Row").prop("disabled", false);
}
$('select').material_select();
});
...
Add HTML code as requested, it's wrapped in a visualforce page, each checkbox will manage text fields on the same row in table.
<table>
...
<tbody>
<tr>
<td>
<apex:inputCheckbox id="cBC1"/>
<label for="j_id0:j_id1:cBC1"></label>
</td>
<td>
<div class="input-field">
<apex:inputField styleClass="validate cBC1_Row"/>
</div>
</td>
<td>
<div class="input-field">
<apex:inputField styleClass="validate cBC1_Row"/>
</div>
</td>
</tr>
<tr>
<td>
<apex:inputCheckbox id="cBC2"/>
<label for="j_id0:j_id1:cBC2"></label>
</td>
<td>
<div class="input-field">
<apex:inputField styleClass="validate cBC2_Row"/>
</div>
</td>
<td>
<div class="input-field inline">
<apex:inputField styleClass="validate cBC2_Row"/>
</div>
</td>
</tr>
</tbody>
</table>
You could drop the last number in the selector, and use "attribute contains" instead, assuming you don't have several elements containing the string cBC.
An other, and better option, would be to use classes
$('[id*=cBC]').on('change', function () {
$(".cBC"+ this.id.match(/\d+$/)[0] +"_Row").prop("disabled", this.checked);
$('select').material_select();
});
Yes, following your pattern you can do:
for (let i = 1; i < amoutOfIds; i++) {
$('[id$=cBC'+i+']').change(function () {
if ($(this).is(':checked')) {
$(".cBC"+i+"_Row").prop("disabled", true);
}
else {
$(".cBC"+i+"_Row").prop("disabled", false);
}
$('select').material_select();
});
}
You have to set correctly the amountOfIds you have, and also you should be changing let i = 1 also to begin with the first id you have.
If you can refactor your event handler to work for each element, you could write a single jquery selector and bind the same anonymous event handler to both elements. It is difficult to determine whether or not this refactoring is feasible without seeing the markup of the elements your script is interacting with.
From your code it seems the IDs are matched.
Why not using:
$('[id^="cBC"]').change(function () {
var _id = $(this).id();
$("."+_id+"_Row").prop("disabled", $(this).is(':checked'));
$('select').material_select();
});

Javascript - Change event trigger multiple times

I have the following table.
<table class="table invoice-items-table">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="invoice-item-row">
<td>
<select class="selectpicker invoice-item-select" title="Select an Item">
<option value="1">PHP Development</option>
</select>
</td>
<td class="text-right">
<input class="form-control invoice-item-quantity" value="1" type="text">
</td>
<td class="text-right">
<input class="form-control invoice-item-price" value="0.00" type="text">
</td>
<td class="text-right" style="padding-top:18px!important;">
<span class="invoice-item-amount">0 </span>
<span class="invoice-currency">₹</span>
</td>
</tr>
<tr class="invoice-item-add-row">
<td colspan="7">
<a href="#" class="link invoice-item-add text-center">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add an Item
</a>
</td>
</tr>
</tbody>
</table>
For on-click event of a.invoice-item-add I append more table rows tr to the table, here is the code for that.
$('.invoice-item-add').on('click', function() {
var itemRowClone = $('.invoice-item-row').last().clone();
itemRowClone.find('input, textarea').val('');
itemRowClone.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
itemRowClone.find('.selectpicker').selectpicker();
$('.invoice-item-add-row').before(itemRowClone);
return false;
});
This works perfectly fine, until I want to trigger select.invoice-item-select, here is how I trigger it.
$(document).on('change', '.invoice-item-select', function() {
// Code here...
});
my problem is, this on-change gets fired multiple times based on the number of elements added dynamically, if there is one tr.invoice-item-row it gets fired twice, if there are two tr.invoice-item-row it gets fired four times, basically it fires times two.
I understand that the tr.invoice-item-row are added dynamically and we are using $(document).on('change', '.invoice-item-select', function()... to listen to the trigger.
How do I make sure this on-change event is fired only once?
Thanks.
$(document).on('change') event should called once on page load. No need to add document change on row add.
OR
You can first unbind event then bind again like
$(document).off('change','.invoice-item-select').on('change', '.invoice-item-select', function() {
// Code here...
});
I ended up using this solution
$(document).on('change', '.invoice-item-select', function(e) {
if (e.handled !== true) {
e.handled = true;
return;
}
// Code here
});
Although this does not stop from multiple firing of events, I can at-least stop the code execution for subsequent triggers.
Below code save my time. Your code should run inside the 'if' function and element's 'click' event. Then you can avoid the item duplication.
$(document).on('click', '.selectpicker', function(e) {
if (e.handled !== true)
{
e.handled = true;
// Your code here
return;
}
});
You can try in alternative way like this,
$('.invoice-item-select.bootstrap-select').on('changed.bs.select', function(){
// your code
});
bootstrap-select class should be applied after loading DOM into the browser.
I hope this will solve your problem.

Show hide input element based on selection

Hi I am trying to show hide input element based on selection value of another element.
However I am unable to achieve it. I am not sure what is wrong I am doing.
The JS Fiddle is here :
https://jsfiddle.net/rovvLt9e/1/
<div>
<table>
<tr id="type">
<td height="30">Type</td>
<td>
<input type="radio" name="type" value="Document" checked>Document
<input type="radio" name="type" value="Parcel">Parcel
</td>
</tr>
</br>
</br>
<tr id="height">
<td height="40">Approx weight of consignment</td>
<td>
<select name="weight">
<option selected>200gms</option>
<option>200 - 500gms</option>
<option>500 - 750gms</option>
<option>750gms - 1Kg</option>
<option>1Kg - 5Kg</option>
<option> > 5Kg</option>
</select>
</td>
</tr>
</table>
</div>
</br></br>
<div id="text"> text</div>
The Jquery is :
$(document).ready(function () {
if ($('#type').val() == "Parcel") {
$('#height').show();
}
else {
$('#height').hide();
}
});
https://jsfiddle.net/rovvLt9e/1/
Try to use change event to accomplish your task,
$(document).ready(function() {
var elem = $('#height');
var radios = $(':radio[name=type]').change(function() {
elem.toggle(radios.filter(":checked").val() == "Parcel");
});
});
And note, you have to use attribute selector here as there was no element with id type.
DEMO
There is no element with id type. Bind change event to input[name=type] and toggle visibility like following.
$('input[name=type]').change(function() {
$('#height').toggle(this.value=="Parcel");
});
$('input[name=type]:checked').change(); //to set initial state
UPDATED FIDDLE
Try using selector #type input , .change() event
$(document).ready(function() {
var h = $("#height");
$("#type input").change(function() {
if (this.checked && this.value == "Parcel") {
h.show();
} else {
h.hide();
}
}).change()
});
jsfiddle https://jsfiddle.net/rovvLt9e/6/

conditionally hide input in table

I am trying to have a select input with an other option when the other option is selected the input should become visible, however I want it defaulted as hidden and it should rehide if select is changed again later. I have tried == and literal === and reversing the hide show commands with != without change
currently I have
HTML:
<tr>
<td colspan="3" align="center" border="1">Certification:</td>
<td colspan="3" align="center" border="1">
<select name="certname" id="certname">
<option value=""> </option>
<option value="State">State</option>
<option value="Other">Other</option>
</select>
<input type="text" id="othercert" name="othercert" />
</td>
</tr>
and JS:
$("#othercert").hide();
$(document).ready(function () {
$("#certname select").change(function (e) {
if ($(this).val() != "Other") {
$("#othercert").hide();
}
else {
$("#othercert").show();
}
});
});
I am unsure where to go from here or what is going wrong - any assistance is appreciated.
Your selector thinks select is the child to #certname rather than its id. It should be:
select#certname and not #certname select
JS Fiddle
$("#othercert").hide();
$(document).ready(function () {
$("select#certname").change(function (e) {
if ($(this).val() != "Other") {
$("#othercert").hide();
} else {
$("#othercert").show();
}
});
});
Your change selector is wrong. The select isn't a child of #certname, therefore change to the following:
$("select#certname").change(function (e) {
http://jsfiddle.net/ndgadeb1/
Also you need to put your initial hide inside the document ready function:
$(document).ready(function () {
$("#othercert").hide();
However if you wish to hide on page load then you can just do this in CSS:
#othercert{
display:none;
}
That way it won't flash on page load.

Categories

Resources