Good morning. I am slowly but surely figuring out jQuery, but this morning I find myself stumped and head-scratching. First, my relevant code:
HTML
<fieldset class="fieldset2">
<legend>Return Specific Curriculum Information</legend>
<input type="hidden" id="ccnt" value="0">
<table class="table" id="retc">
<thead>
<tr>
<th class="th">#</th>
<th class="th">Year</th>
<th class="th">Lang</th>
<th class="th">Week/Packet</th>
<th class="th">Quantity</th>
<th class="th">Delete</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input type="button" value="Add Curriculum To Return" class="button" id="addcurric">
<input type="button" value="Remove All Entries" class="button" id="remcurric">
</fieldset>
JavaScript/jQuery
$('#ccnt').data('count', 0);
$('#addcurric').click(function () {
function getcount() {
var $this = $('#ccnt'),
count = $this.data('count') + 1;
$this.data('count', count);
return count;
}
var mycount = getcount();
var myyear = 'cyear' + mycount;
var mylang = 'clang' + mycount;
var myweek = 'cweek' + mycount;
var myqty = 'cqty' + mycount;
alert('mycount: ' + mycount + '; myyear: ' + myyear + '; mylang: ' + mylang + '; myweek: ' + myweek + '; myqty: ' + myqty);
var tdclass;
if (mycount % 2 == 1) {
tdclass = "td1";
} else {
tdclass = "td2";
}
var chtml = "";
chtml += "'<tr>";
chtml += " <td class=\"" + tdclass + "\">" + mycount + "</td>\n";
chtml += " <td class=\"" + tdclass + "\"><select name=\"" + myyear + "\" id=\"" + myyear + "\">\n";
chtml += " <option value=\"0\">-- Select --</option>\n";
chtml += " <option value=\"1\">Year 1</option>\n";
chtml += " <option value=\"2\">Year 2</option>\n";
chtml += " <option value=\"3\">Year 3</option>\n";
chtml += " </select></td>\\n";
chtml += " <td class=\"" + tdclass + "\"><select name=\"" + mylang + "\" id=\"" + mylang + "\">\n";
chtml += " <option value=\"0\">-- Select --</option>\n";
chtml += " <option value=\"1\">English</option>\n";
chtml += " <option value=\"2\">Spanish</option>\n";
chtml += " </select></td>\\n";
chtml += " <td class=\"" + tdclass + "\"><select name=\"" + myweek + "\" id=\"" + myweek + "\">\n";
chtml += "";
chtml += " </select></td>\n";
chtml += " <td class=\"" + tdclass + "\"><input type=\"text\" name=\"" + myqty + "\" class=\"input\"></td>\n";
chtml += " <td class=\"" + tdclass + "\"><button type=\"button\" class=\"dbutton\" title=\"Remove This Row\">X</button></td>\n";
chtml += " </tr>\n'";
$('#retc > tbody').append(chtml);
$(".dbutton").bind("click", Delete);
});
$('#remcurric').click(function () {
$('#retc > tbody').html("");
$('#ccnt').data('count', 0);
});
function Delete() {
var par = $(this).parent().parent();
par.remove();
}
The Problem/Question
As you can see, in my js/jQ code, I am generating dynamic table rows to handle 1-n records. I also left a blank where option lines should be for id "myweek" - because they should come from my database. Ordinarily, I would do something like this to fill those in:
$('#'+mylang).change(function() {
var lang = $('#'+mylang).val();
var year = $('#'+myyear).val();
$.post("/chairs-dev/jqf/returncurric_processajax.php", {LANG: lang, YEAR: year}, function (data) {
$('#'+myweek).append(data);
});
});
This code didn't work, so I went code hunting online. I have tried about every permutation I can think of or find online to solve this issue, but none of it works. I am sure there is something basic I'm missing here, but I just can't see it. Any thoughts on how I can get this to work?
Thanks in advance!!
EDIT: Sorry, jsfiddle link
Here's one approach. Step 1 would be to fix the existing Delete click function. You are going to end up assigning multiple click event handlers this way. Step 2 would be to adjust your change method. Here's how I got it working:
// remove your other `.dbutton` click handler
$('#retc').on('click', 'button.dbutton', Delete);
// add a proper change event
$('#retc').on('change', 'select[name^="clang"]', function() {
var lang = $(this).val();
var year = $(this).parents('tr').find('[name^="cyear"]').val();
//alert('lang: ' + lang + ', year = ' + year);
var $myweek = $(this).parents('tr').find('[name^="cweek"]');
$.post("/chairs-dev/jqf/returncurric_processajax.php", {LANG: lang, YEAR: year}, function (data) {
$myweek.html(data);
});
});
jsFiddle Demo
Like Corey Mentioned, when you call .change, it only binds to elements that exist currently.
To make it work for elements added to the page later you can bind the change function to the document and add a selector.
Something like this should work for elements added later on...
$(document).on('change', '#' + mylang, function(){
alert('Element changed');
});
Related
I'm trying to insert a button in the end of each row of the table receitas but the buttons are being set at the start of the table instead of the end of each row.
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for(let i in receitas) {
if(receitas[i].tipo==aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> '+ receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td></td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
The line where I put all the properties into the table row (inside of for), I have an input which should be set at the end of the row but instead, it is going to the top of the table.
It's just a type error in the cell wrapping the button you're creating </td> instead of starting <td>
see belown snippet :
receitas = [
{tipo:"typ1",nome:"nome1",tempo:"tempo1",custo:"custo1",dificuldade:"dificuldade1"},
{tipo:"typ2",nome:"nome2",tempo:"tempo2",custo:"custo2",dificuldade:"dificuldade2"},
{tipo:"typ1",nome:"nome3",tempo:"tempo3",custo:"custo3",dificuldade:"dificuldade3"},
{tipo:"typ1",nome:"nome4",tempo:"tempo4",custo:"custo4",dificuldade:"dificuldade4"},
]
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for (let i in receitas) {
if (receitas[i].tipo == aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> ' + receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td><td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
mostraTabelaTeste("typ1","table");
<div id="table"></div>
You may need to add one more th for button column in first row. Like below:
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th><th> </th></tr>';
Here is my dropdownlist:
<div id="addCam"></div>
<div id="addDiv">
<select id="type1">
<option value="">- Kiểu áo -</option>
#foreach (var item in Model.teetypes)
{
<option value="#item.Image">#item.Name</option>
}
</select>
<a class="btn btn-info btn-default" id="addBtnH" style="text-align:center" title="Thêm sản phẩm"><i class="fa fa-plus"></i></a>
</div>
Button submit:
<input type="submit" value="Khởi động chiến dịch" onclick="return validate()" class="btn btn-success btn-lg" />
Javascript .append():
$(document).ready(function () {
var count = 2;
var maxAppend = 0;
$("#addBtnH").click(function () {
var name = $("#type1 option:selected").val();
var name1 = $("#type1 option:selected").text();
if (name == '') return;
if (maxAppend >= 5) {
$("#addDiv").hide();
return;
}
$("#addDiv").show();
$("#addCam").append("<div class='widget' id='del" + count + "'><div class='widget-body'><div class='col-md-3'><span style='display:block'><img src='/Content/assets/img/avatars/" + name + ".png' title='"+name+"' id='tee" + count + "' height='75'/></span></div>" +
"<div class='col-md-1'><select id='color" + count + "' onchange='changeColor" + count + "()'>#foreach (var item in Model.teecolors){<option value='#item.Color' style='background-color: ##item.Color'></option>}</select></div><div id='dis" + count + "'>" + name1 + "</div><input type='hidden' id='diss" + count + "'>" + name1 + "</div>" +
"<hr class='wide'><input type='text' name='input'><a class='btn btn-info btn-default' rel='"+name+"' id='delete" + count + "' style='text-align:center' title='Xóa sản phẩm'><i class='fa fa-trash'></i></a>" +
"<script>$('#delete" + count + "').click(function(){var rel = $('#tee"+count+"').attr('title'); $('#type1 option[value = '+rel.toString()+']').unwrap();$('#del" + count + "').remove();});" + "<" + "/script>" +
"<script type='text/javascript'>function changeColor" + count + "(){var eID = document.getElementById('color" + count + "'); var colorVal = eID.options[eID.selectedIndex].value; document.getElementById('tee" + count + "').style.background = '#' + colorVal;}" + "<" + "/script>" +
"</div></div>");
count = count + 1;
maxAppend++;
$("#type1 option:selected").wrap('<span/>');
$("#type1").val('');
});
});
I have name and name1 for get value and text of dropdown from db to display in .append() when click button add. With this code, could I save all value option had been added to new table in database? how to do that in controller? Or I have to rewrite the javascript .append()?
My controller name is CreateCampaign.
Thanks for any help.
Append it to some form and then serilize. For example:
<form id="myForm">
...
</form>
$('btn').click(function(){
$('#myForm').append(...)
});
$('#myForm').on('submit', function(){
$.post(url, $( this ).serialize() ...
});
In Controller you shoud have array or list something like this :
string [] name1
or use FormCollection
Here is my dropdownlist:
<div id="addCam"></div>
<div id="addDiv">
<select id="type1">
<option value="">- Kiểu áo -</option>
#foreach (var item in Model.teetypes)
{
<option value="#item.Image">#item.Name</option>
}
</select>
<a class="btn btn-info btn-default" id="addBtnH" style="text-align:center" title="Thêm sản phẩm"><i class="fa fa-plus"></i></a>
</div>
And here is my javascript .append():
$(document).ready(function () {
var count = 2;
var maxAppend = 0;
$("#addBtnH").click(function () {
var name = $("#type1 option:selected").val();
var name1 = $("#type1 option:selected").text();
if (name == '') return;
if (maxAppend >= 5) {
$("#addDiv").hide();
return;
}
$("#addDiv").show();
$("#type1 option:selected").attr('disabled', 'disabled');
$("#type1").val('');
$("#addCam").append("<div class='widget' id='del" + count + "'><div class='widget-body'><div class='col-md-3'><span style='display:block'><img src='" + name + "' id='tee" + count + "' height='75'/></span></div>" +
"<div class='col-md-1'><select id='color" + count + "' onchange='changeColor" + count + "()'>#foreach (var item in Model.teecolors){<option value='#item.Color' style='background-color: ##item.Color'></option>}</select></div><div id='dis" + count + "'>" + name1 + "</div>" +
"<hr class='wide'><input type='text' name='input'><a class='btn btn-info btn-default' rel='"+name+"' id='delete" + count + "' style='text-align:center' title='Xóa sản phẩm'><i class='fa fa-trash'></i></a>" + #*str +*#
"<script>$('#delete" + count + "').click(function(){var images = $(this).attr('rel'); $('#type1 option[value = "+"images"+"]').removeAttr('disabled');$('#del" + count + "').remove();});" + "<" + "/script>" +
"<script type='text/javascript'>function changeColor" + count + "(){var eID = document.getElementById('color" + count + "'); var colorVal = eID.options[eID.selectedIndex].value; document.getElementById('tee" + count + "').style.background = '#' + colorVal;}" + "<" + "/script>" +
"</div></div>");
count = count + 1;
maxAppend++;
});
});
My problem is, when I click button add, it will add div as content in append, and the value has been add will be disabled in dropdownlist. In the added div, there is a button delete, when i click it, the div will disappear, and the disabled attribute value will be remove. I create 'images' to get attr('rel') of that button, but i don't know how to let $("#type1 option[value=images]") understand that 'images' is a value, not a string? Please help me!
It is not the best practice to write the scirpts elements into the code to be evaluated.
The technique you are looking for is to continuously use jquery selector to get the appended node and set the attributes dynamically.
Consider this solution:
$("#addCam").append($('<ul>').attr('class', 'some-class')
.append($('<li>').attr('class', 'some-other-class')
.append($('<img>').attr('src', 'somePath'))
.on('click', liClickedHandler)));
I am trying to prevent the player from getting added again with the new value, rather I would like to just update the quantity..
HTML
<div class="playerTypeBlock" data-player-type-id="1" data-player-value="10.00">
<div class="heading">Ninja</div>
<div class="price">$10</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<div class="playerTypeBlock" data-player-type-id="2" data-player-value="20.25">
<div class="heading">Samurai</div>
<div class="price">$20.25</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<table class="teams" border="1">
<thead>
<tr>
<th>Players</th>
<th>Quantity</th>
</tr>
</thead>
<tbody class="totalPlayers"></tbody>
</table>
<div class="total">
<span>Total: $</span>
<span class="amount" id="totalvalue">0.00</span>
</div>
I tried using this when appending the table row, but not getting the desired result
JavaScript
var addToTeam = document.getElementsByClassName('addToTeam'),
parentElement = document.getElementsByClassName('playerTypeBlock'),
playerName = document.getElementsByClassName('heading'),
totalVal = document.getElementById('totalvalue'),
tableBody = document.querySelector('.totalPlayers');
var updatePlayers = function (evt) {
evt.preventDefault();
var amount = totalVal.innerHTML,
productId = this.parentElement.getAttribute('data-player-type-id'),
productPrice = this.parentElement.getAttribute('data-player-value'),
playerName = this.parentNode.querySelector('.heading').innerHTML,
updateTotal = parseFloat(amount) + parseFloat(productPrice);
var quantity = parseInt($(this).data('click'), 10) || 0;
quantity++;
$(this).data('click', quantity);
totalVal.innerHTML = Math.round(updateTotal * 100) / 100;
//adding the the table row here...
$('table .totalPlayers').append('<tr><td>' + playerName + '</td><td>' + quantity + ' </td></tr>');
};
for (var i = 0; i < addToTeam.length; i++) {
addToTeam[i].addEventListener('click', updatePlayers);
}
See Demo
Check quantity and append new row if it's 1 otherwise modify quantity cell:
if (quantity > 1) {
$('table .totalPlayers').find('#player-' + playerId + ' .quantity').text(quantity);
}
else {
$('table .totalPlayers').append('<tr id="player-' + playerId + '"><td>' + playerName + '</td><td class="quantity">' + quantity + ' </td></tr>');
}
Demo: http://jsfiddle.net/zx65uv8a/12/
This line the problem?
$('table .totalPlayers').append(
'<tr><td>' + playerName + '</td>' +
'<td>' + quantity + ' </td></tr>');
You are using append() so you'll always be adding and not replacing.
If you can add something unique to a class or id then you can replace it that way. i.e.
$('table .totalPlayers').append(
'<tr id="' + playerId + '">' +
'<td>' + playerName + '</td>' +
'<td class="quantity">' + quantity + ' </td></tr>');
Then to update
$('#' + playerId + ' .quantity').html(New value here);
I have a webpage that based on user input populates with form fields, as done by the following:
function Go2() {
var loans = document.getElementById('count').value;
var content = document.getElementById('stage3').innerHTML;
content = '<TABLE Width="100%">'
+'<TR>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Name</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Customer Number</TD>'
+'<TD Style="font-weight:bold;" Width="30%">Origination Date</TD>'
+'</TR>'
+'</TABLE>';
document.getElementById('stage3').innerHTML = content;
for(var i=0; i<loans; i++) {
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE Width="100%">'
+ '<TR>'
+ '<TD Width="30%"><INPUT Name="CName'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="CNumber'
+ i
+ '" Size="40" Type="text"></TD>'
+ '<TD Width="30%"><INPUT Name="Date'
+ i
+ '" Size="40" Type="text"></TD>'
+ '</TR>'
+ '</TABLE>';
}
content = document.getElementById('stage3').innerHTML;
document.getElementById('stage3').innerHTML = content
+ '<TABLE><TR><TD><INPUT Type="Button" Value="Submit" onClick="Go3()"></TD></TR></TABLE>';
}
Now what I need to do is iterate through the form and pull out the values for each of the form fields. This is about as far as I've gotten:
for (var n=0; n<loans; n++) {
content += '<TR>'
+ '<TD Colspan="2">'
+ document.getElementById('CName + n').value
+ '</TD>'
+ '<TD Colspan="2">'
+ document.getElementById('CNumber + n').value
+ '</TD>'
+ '<TD>'
+ document.getElementById('Date + n').value
+ '</TD>'
+ '</TR>';
}
Which does...Nothing. The last notable progress I had was getting it to spit out "null" which isn't really progress at all. I've looked at eval, but there's quite a few warnings against it.
Any Ideas?
I think you want
document.getElementById('CName' + n).value
(where n is outside of the quotes)
Well it should be 'CName' + n - i.e., you got the quotation marks in the wrong place
If all your controls are in a form, then you can access them as:
var allControls = document.<formId>.elements;
or
var allControls = document.forms[formId].elements;
Then iterate over the list of controls to get the values. The form controls must have names to be successful, no need for IDs. You can also get the values as:
var value = allControls['CName' + n].value;
or just
var form = docment.forms[formID];
var value = form['CName' + n].value;