How to get script's value in .append()? - javascript

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

Related

Problem in writing a razor code in Script

This is my code. I want to create two textboxes using Razor in script.
the model=>model[i].Name1 is not woring
var counter = 0;
#{
int i = 0;
}
$(document).ready(function () {
$("#addButton").click(function () {
if (counter < 0) {
alert("Add more textbox");
return false;
}
i = counter;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter).attr("class", 'TextBoxDiv').attr("style", "border:5px solid green");
newTextBoxDiv.after().html('<label>Name #'+ counter + ': </label>' +
'#Html.EditorFor(model => model[i].Name1);' +
'<br/> <label>Email #'+ counter +': </label>' +
'#Html.EditorFor(model => model[i].EmailID);' +
'<br/><input type="button" name="button' + counter +
'" class="removeButton" id="removeButton' + counter + '" value="Remove Button" onclick="remove(this)">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
alert(i.toString());
counter++;
i = i + 1;
});
});
You cannot get JS to write out Razor - the JS happens client side AFTER the razor has been executed on the server and sent to the client. the JS won't know what to do with the razor syntax.
In this case, you would need to manually create the html which the Razor helper would make for you. It should still parse back into razor, providing you put the html in the right format (right name, id etc)
So write out the and make the name field match what the razor would have generated.
You can try to set a js variable with the value of model,and then use <input/> to replace #Html.EditorFor():
var counter = 0;
var m = JSON.parse('#Json.Serialize(#Model)');
$(document).ready(function () {
$("#addButton").click(function () {
if (counter < 0) {
alert("Add more textbox");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter).attr("class", 'TextBoxDiv').attr("style", "border:5px solid green");
newTextBoxDiv.after().html('<label>Name #'+ counter + ': </label>' +
'<input id="model_' + counter +'__Name1" name=" model[' + counter + '].Name1" value="' + m[counter].Name1 + '"/>' +
'<br/> <label>Email #'+ counter +': </label>' +
'<input id="model_' + counter +'EmailID" name=" model[' + counter + '].EmailID" value="' + m[counter].EmailID + '"/>' +
'<br/><input type="button" name="button' + counter +
'" class="removeButton" id="removeButton' + counter + '" value="Remove Button" onclick="remove(this)">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});

Button click not working on dynamically created table row

I've tried a few different variations of this but for some reason, none of it seems to be working for me.
I issue an ajax get and loop through the response to print rows to the html.
Each row has a button to delete that element from the row.
It's a little bit lengthy, but here is that ajax get with how I run through the response to append rows to the table.
function getIEXSymbolQuote(symbol) {
$.ajax({
url: IEXurlBase + "/stock/" + symbol + "/quote",
method: "GET",
success: function (data) {
symbol = data.symbol;
companyName = data.companyName;
change = data.change;
changePercent = data.changePercent * 100;
changePercent = changePercent.toFixed(2);
iexRealtimePrice = data.iexRealtimePrice;
iexRealtimePrice = iexRealtimePrice.toLocaleString();
close = data.close;
close = close.toLocaleString();
if (iexRealtimePrice === null) {
if (change > 0) {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + latestPrice + "</small></td><td class='positive-data'><small>$" + change + "</small></td><td class='positive-data'><small>+" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
} else {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + latestPrice + "</small></td><td style='color: red'><small>$" + change + "</small></td><td style='color: red'><small>" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
}
} else {
if (change > 0) {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + iexRealtimePrice + "</small></td><td class='positive-data'><small>$" + change + "</small></td><td class='positive-data'><small>+" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
} else {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small >$" + iexRealtimePrice + "</small></td><td style='color: red'><small>$" + change + "</small></td><td style='color: red'><small>" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
}
}
$('#watchListTable').css('visibility', 'visible');
$('#watchListErrBox').css('visibility', 'hidden');
},
error: function (err) {
$('#watchListErrBox').css('visibility', 'visible');
}
})
}
I need to be able to click on one of the trash buttons and get the id of the button clicked.
I've tried:
$("button").on("click", "button.removeWatchListitem", function () {
event.preventDefault();
alert($(this.id));
});
And;
$(".removeWatchListitem").on("click", function () {
event.preventDefault();
alert($(this.id));
});
but neither fire. This should be simple but I don't know if I'm just having a massive brain fart.
Add eventlistener to an exist div,such as body.
$(body).on('click','.removeWatchListitem',function(){...});

Get and save value had been add from dropdownlist to database

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

jquery $('id').change inside $('id2').click?

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

How to stop from appeding the the value to just updating the value in jQuery?

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

Categories

Resources