I have a loop which is creating table:
for(m=1; m<7; m++){
document.getElementById('content').innerHTML +=
('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>')
}
In every row in second TD is button which must be assigned to every row. Each button has his own row. I want to alert m from the first TD exactly when i click button from that row. I mean if i will click button is switch2 i will get alert from m "2".
Here is the button code i tried:
var buttons = "#switch" + m
$(function() {
$(buttons).button();
$(buttons).click(function(){
alert(m);
});
});
This is not working because all of the buttons alerting last value from loop = 6.
I know it is confused but i hope you uderstand. Really appreciate your help
Change it to this:
$(function() {
var localM = m;
$(buttons).button();
$(buttons).click(function(){
alert(localM);
});
});
The problem is the alert binds to the variable m not the value of m. By allocating a local variable inside the closure you capture the value of m at that point in the loop.
you can also bind event another way, for sample
$("tr > td > input[type=checkbox]").function(e){
alert(event.target.id);
//OR
alert(this.id);
});
if you can add any class attribute in element
Then this is safe
$("tr > td > input[type=checkbox].switch").function(){
alert(event.target.id);
});
There is so many ways to do this. Here's one:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Populate Form
for (var m = 1; m <= 7; m++)
{
$('#content').append('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" class="clickMe" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>');
}
// Handle Click
$('.clickMe').click(function()
{
alert('You clicked on : ' + $(this).attr('id')); // alerts "switchN" e.g. switch1
// or //
alert('You clicked on : ' + $(this).attr('id').replace('switch', '')); // // alerts "N" e.g. 1
});
});
</script>
<table id="content"></table>
Here's a bit of a refactor (minus the button() plugin):
var $content = $('#content');
for (var m = 1; m < 7; m++) {
$content.append(
'<tr>' +
'<td>' + m + '</td>' +
'<td>' +
'<input type="checkbox" id="switch' + m + '">' +
'<label class="switch" data-num=' + m + ' for="switch' + m +'">Button ' + m + '</label>' +
'</td>' +
'</tr>'
);
}
$('label.switch').click(function(e) {
e.preventDefault();
alert($(this).data('num'));
});
JSFIDDLE
Related
Hi people i have a dynamic table (add rows from ajax requests) and i need sum and multiply values always (without a trigger event).
i have already a functions that make it with the event (blur) but i don't wanna make it by using the blur trigger.
There is a way for do it?
My code:
$.fn.sumValues = function() {
var sum = 0;
this.each(function() {
if ($(this).is(':input')) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
});
return sum;
};
function totaliza() {
var total_recep = $('input[name^="costot"]').sumValues();
$('#total_art').val(total_recep);
}
var counter = 0;
$(document).on('click', '#bt_add', function(e) {
counter++;
var tr = '<tr id="art_' + counter + '">';
tr = tr + '<td><button name="del_art' + counter + '" id="del_art' + counter + '" class="btn btn-default btn-xs del_art" type="button">DEL</button></td>';
tr = tr + '<td><input name="cbarra' + counter + '" id="cbarra' + counter + '" class="form-control" value="02020202" readonly></td>';
tr = tr + '<td><input name="art' + counter + '" id="art' + counter + '" class="form-control" value="ARTICULO" readonly></td>';
tr = tr + '<td><select name="und' + counter + '" id="und' + counter + '" class="form-control list"></select></td>';
tr = tr + '<td><input name="cal' + counter + '" id="cant' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="cal' + counter + '" id="costou' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="costot' + counter + '" id="costot' + counter + '" class="form-control cal" readonly value="0"></td>';
tr = tr + '</tr>';
$("#inv_recep_det tbody").append(tr);
$('.form-control').change(function() {
var number = this.name.replace('cal', '');
var costot = ($('#cant' + number).val() * $('#costou' + number).val())
$('input[name^="costot' + number + '"]').val(costot);
totaliza();
});
$('.del_art').click(function() {
var number = this.name.replace('del_art', '');
$('#art_' + number).remove();
totaliza();
});
});
https://jsfiddle.net/JuJoGuAl/kpLs9zcg/
Something like that?
http://jsfiddle.net/JuJoGuAl/0vx64u2y/
Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/
I have a table where I want to show the last column only if the column before is hovered. The table data is parsed with JSON.
<script type="text/javascript">
$( document ).ready(function() {
var tag_id = $('#tag_id_hidden').val();
$.getJSON("/tags/get_who_tagged/" + '{{tag.tag_id}}' + "/", function(data) {
var lines = '';
for (var i = 0; i < data.length; i++) {
lines += '<tr id="' + data[i]['entity_id'] + '">';
lines += '<td id="button_id"><button id="prefix_' + data[i]["entity_id"] + '" class="js-programmatic-set-val" value="' + data[i]["entity_id"] + '" name="' + data[i]["title"] + '"><i class="fa fa-plus"></i></button></td>';
lines += '<td>' + data[i]['title'] + '</td>';
lines += '<td id="hover_' + data[i]["entity_id"] + '">' + data[i]['count'] + '</td>';
lines += '<td id="hidden_' + data[i]["entity_id"] + '" style="display:none;">'
for (var j = 0; j < data[i]['usernames'].length; j++) {
lines += data[i]['usernames'][j]['username'] + ', '
}
lines += '</td>';
lines += '</tr>';
//$("#count_user_table").empty();
$('#count_user_table tbody').html(lines);
}
});
});
</script>
<script>
$(document).on("mouseenter", "#hover_9242411", function() {$("#hidden_9242411").show();
});
$(document).on("mouseleave", "#hover_9242411", function() {$("#hidden_9242411").hide();
});
</script>
in the example above the code is working but I have to reference the id as "#hover_9242411" and "#hidden_9242411". the part after hover_/hidden_ is dynamically added to each column with a for loop. How can I dynamically reference the second part (9242411)?
Consider modifying your hover cell to something like this:
'<td id="hover_' + data[i]["entity_id"] + '" class="hover-cell" data-target="#hidden_' + data[i]["entity_id"] + '">'
You could then simply use:
$(document).on("mouseover", ".hover-cell", function() {
var target = $(this).data('target');
$(target).show();
});
Fiddle
If it will always be the previous column showing/hiding the next column, you could write your event handlers like this
$('#mytable').on('mouseenter', 'td.hover-column', function(){
$(this).next().show();
}).on('mouseleave', 'td.hover-column', function(){
$(this).next().hide();
});
For that example to work you would need to add a class to the hover column (the one that you want to hover over in order to show the next column). I also gave an id to the table and assigned the event handler to it so the event doesnt have to bubble all the way to the top.
Here is a fiddle
If later on you find that you arent showing/hiding the NEXT column but some other one, you could also put a specific class on that hidden column and instead of using
$(this).next().show();
you could use something like
$(this).closest('tr').find('td.hidden-column').show();
//Display
for (var z=0; z<n; z++) {
document.write("<tr><td>"+ z + "</td>"); // Serial
document.write("<td>" + RandonValue + "</td>"); // Random Number
document.write('<td><button onclick="reply_click()" id="button-' + z + '">Click me</button></td></tr>'); //onClick
}
//Set ID
function reply_click(clicked_id){
alert(clicked_id);
}
Somehow I got undefined for all of them.
The replay_click is only for checking, I want to change that when I have different IDs.
Your z variable is the counter in this case which you can use for your id, keep in mind you can't have an ID starting with a number.
document.write('<td><button onclick="somefunction" id="button-' + z + '">Click me</button></td></tr>');
I have created a fiddle for you. Check it. I hope it fulfills the requirements :)
https://jsbin.com/doxusi/edit?html,js,output
<table id="mytable"></table>
var html = '';
var random = 5;
for (var i = 1; i <= random; i++) {
html += '<tr>' +
'<td>' + i + '</td>' +
'<td>Some Number</td>' +
'<td><button id="id_' + i + '">Button ' + i + '</button></tr></td>';
}
document.getElementById('mytable').innerHTML = (html);
You can inject your z variable like this, also putting double quotes (best practice:
document.write('<td><button onclick="somefunction(this)" id="mycell-' + z + '">Click me</button></td></tr>');
Note that you better pass this to your function, so inside that function you can reference that id:
function somefunction(elem) {
alert('you clicked ' + elem.id);
}
html code:
<div id="localPropList"></div>
<div id="assignedPropList"> </div>
js code:
function getLocalProposals()
{ // filling these radio buttons dynamically
var htmlStringLocalPro = '<fieldset id="local_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var k = 0; k < result.rows.length; k++) {
var localProposal = result.rows.item(k);
if( !(jQuery.inArray( localProposal.id, arrForQueuePropId ) >=0 ) )
{var fieldId = 'localPro' + k;
htmlStringLocalPro += '<input group="1" type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + localProposal.enquiry_no + ',' + localProposal.id + '"/>'
+ '<label for="' + fieldId + '" data-iconpos="right">' + localProposal.enquiry_no+'-'+localProposal.caller_name+'</label>';
}
htmlStringLocalPro += '</fieldset>';
}
function getAssignedproposals()
{
var htmlString = '<fieldset id="assigned_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var i = 0;i < obj.Proposal.length; i++) {
proposalIds += obj.Proposal[i].id + ',';
if( !(jQuery.inArray( obj.Proposal[i].id, arrForQueuePropId ) >=0 ) ){
var fieldId = 'ap' + i;
htmlString += '<input group="1" type="radio" name="assigned_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
// htmlString += '<input type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
}
}
htmlString += '</fieldset>';}
$("input:radio[name=local_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
$("input:radio[name=queue_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
i need to select only one radio button at a time if radiobutton having name="assigned_proposal_id" is selected then it should not allow to select any radio buttons for name="local_proposal_id]" i cannot assign id different i need to do selection on the basis of name and i cant assign same name to separate group as well
please tell me whats the solution
Checking / Unchecking in jQuery Mobile, you need to use .prop to checked or unchecked and then call .checkboxradio('refresh').
Demo
$(document).on('pageinit', function () {
$(document).on('change', '[type=radio]', function (e) {
// Uncheck radio buttons in #group1 and #group2
$('#group1 [type=radio]:checked, #group2 [type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// "OR" to select all radio buttons in DOM
$('[type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// Check clicked radio
$(this).prop('checked', true).checkboxradio('refresh');
});
});
try the following
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
$('input [name="assigned_proposal_id"]').click(function(){
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
});
It will work like what hussain told
Here A FIDDLE for your purpose. It will uncheck all the radio button, then check the one we clicked on.
HTML :
<div id="localPropList">
<input name="assigned_proposal_id" type="radio" value="value1-1" />value1-1
<input name="assigned_proposal_id" type="radio" value="value1-2" />value1-2
<input name="assigned_proposal_id" type="radio" value="value1-3" />value1-3
</div>
<br/>
<div id="assignedPropList">
<input name="local_proposal_id" type="radio" value="value2-1" />value2-1
<input name="local_proposal_id" type="radio" value="value2-2" />value2-2
<input name="local_proposal_id" type="radio" value="value2-3" />value2-3
</div>
div selected : <span></span>
JQUERY :
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').change(function(){
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').prop('checked', false);
$(this).prop('checked', true);
$('span').html($(this).val());
});
Disable Syntax:
$('input[name="name_here"]').attr('disabled', 'disabled');
Don't go for the hardest thing
Hussein Nazzal is correct but space matters
between input and '[' bracket
if($('input[name="assigned_proposal_id"]:checked').val() != '')
{
$('input[name="local_proposal_id"]:radio').attr('disabled', 'disabled');
}
Demo
This worked for me, take into account that according to the selector this change will apply to all RadioButtons in the document with the same class, in this case class="chartIndex":
$(".chartIndex").change(function () {
$('[type=radio]:checked').prop('checked', false);
$(this).prop('checked', 'checked');
});
Hope this helps someone. Regards.
I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);