How to iterate js function? - javascript

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();
});

Related

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.

Click event also firing when check box check event within a row gets fired

I have checkboxes within table individual rows.
I want some event to get fired , when elsewhere in the row click happens . But when a checkbox is checked , I do not want to fire any event.
This is my markup.
<tbody data-bind="foreach:CustomerList">
<tr onclick="removepage();" onmouseover="changeRowColor(this)" onmouseout="restoreRowColor(this)">
<td>
<input class="checkbox" data-bind="attr: { Id: 'checkbox' + $data.Id },click:$parent.customerClick" type="checkbox">
</td>
<td class="col-md-4">
<span class="name" data-bind="text:customerName" />
</td>
<td>
<span data-bind="text:siteName" />
</td>
</tr>
</tbody>
So , if removepage() gets fired for everything , when
customerClick() happens , I do not want the removepage() to get fired.
I tried
customerClick: function () {
debugger;
e.stopPropagation();
},
but it did not work.
What did I do wrong ?
your customerClick function should be:
customerClick: function (event) {
event.stopPropagation();
}
,
You are using e without adding it as a parameter for the function
so just add e in your function()
customerClick: function(e) {
e.stopPropagation();
},
In java script you can stop the bubbling of event listner, because you have a few that listenrs to your event you can stop bubbling it to the other events...
event.stopPropagation()
is the method you looking for
You should bind your events like this:
$("#test > tbody > tr")
.on("click", "td:not(.notfiring)", function(){
alert("click tr");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="test">
<tbody>
<tr>
<td class="notfiring">
<input class="checkbox" type="checkbox">
</td>
<td>
Col 1
</td>
<td>
Col 2
</td>
</tr>
</tbody>
</table>
I hope this helps you

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/

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

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.

Select all checkbox not working

I have been using bootstrap tables to fetch data from database using kendo datasource. So in order to make it more interactive i have used a checkbox for simultaneous actions.
I want to delete all the entries with one checkbox. I have read about deleting entries with single checkbox using jQuery. But problem is that I have only one checkbox in table and all the entries are being fetched using kendo data source.
If i am creating confusion then see here-
<script id="template" type="text/x-kendo-template">
<tr>
<td>
<input type="checkbox" class="done" data-id="#= CID #" ></input>
</td></tr>
</script>
<table>
<tr>
<th style="width:10%;">
<input type="checkbox" />
</th>
</tr>
</table>
Now with using kendo datasource i have one column of checkboxes only.
So i am doing this-
<script type="text/javascript">
$('.done').click(function (event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
}
});
</script>
And still no result. Help!
Try to wrap your jQuery code inside $(document).ready(function(){}); or $(function(){}); to let it see the whole DOM:
$(document).ready(function() {
$('.done').click(function (event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function () {
this.checked = true;
});
}
});
});
Also, your HTML are wrapped inside the script tag, move it outside and remove redundant ' as well as the input tag doesn't need a closing </input> tag:
<tr>
<td>
<input type="checkbox" class="done" data-id="#= CID #" />
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$('.done').click(function (event) {
if ($(this).attr('checked')) {
$('input:checkbox:not(".done")').each(function () {
$(this).attr('checked', 'checked');
});
}
});
});
</script>
Try this. it may works
Try this:
$(function () {
$('.done').on('click', function(){
// i comment this condition if you want selectall for checked or unchecked
//if ($(this).is(':checked')){
$(':checkbox').prop('checked', this.checked);
//}
});
});
Just try this:
Script
$(document).ready(function(){
$('.done').click(function (event) {
$('.chkbxq').each(function () {
$(this).attr('checked', flag);
});
});
});
HTML:
<table>
<tr>
<th style="width:10%;">
<input type="checkbox" class="chkbxq" />
</th>
</tr>
</table>

Categories

Resources