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++;
});
});
Related
I am just learning jquery and javascript and i have a function that unwraps [select] elements on my page and displays them as buttons. There could be multiple select boxes on my page so I need to dynanically name the following variables based on the elementname that is passed in, so that when the buttons are clicked it passed the correct values:
selector1
currentvalue1
hidden1
svalue1
This is the function:
function doUnwrap(elementname) {
var selector1 = document.getElementById('' + elementname + '');
var currentvalue1 = selector1[selector1.selectedIndex].text;
var hidden1 = $('<input type="hidden" name="' + elementname + '">');
hidden1.val($('[name=' + elementname + ']').val());
hidden1.insertAfter($('[name=' + elementname + ']'));
$("[name=" + elementname + "] option").unwrap().each(function () {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '">' + $(this).text() + '</div>');
if ($(this).text() == currentvalue[i]) {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
if ($(this).is(':checked')) btn.addClass('on');
$(this).replaceWith(btn);
} else {
var btn = $('<div class="btn" id="' + $(this).attr('value') + '" >' + $(this).text() + '</div>');
$(this).replaceWith(btn);
};
});
$(document).on('click', '.btn', function () {
$('.btn').removeClass('on');
$(this).addClass('on');
$('input[name=' + elementname + ']').val($(this).text());
var sValue1 = "&value=" + elementname + "|" + $(this).attr('id') + "";
executeAjaxEvent(sValue1, null, "ComboBoxAjaxHandler", false, null, true);
});
}
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/
With the help of http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-add-remove-textbox.html , I got my dynamic inputs and value.
But while adding its concatenating or getting Nan. I need to add values.
var counter = 2;
$("#addButton").click(function () {
if(counter>20){
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
' <div class="col-md-6 marg-top-10 "> <input type="text" class="form-control inputData" name="assetDescription' + counter +
'" id="assetDescription' + counter + '" value="" > </input> </div>' +
' <div class="col-md-6 marg-top-10 "> <input type="text" class="form-control inputData" name="textbox' + counter +
'" id="textbox' + counter + '" value="" > </input> </div>'
);
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
for adding value
$("#getButtonValue").click(function () {
console.log("came ");
var msg = '';
var totalvalue;
var result;
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
result += Number($('#textbox' + i).val());
console.log(result);
}
result is = Nan
help please!
try with this..
var result = 0;
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
result += Number($('#textbox' + i).val());
console.log(result);
}
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)));
See below code. I am creating 2 text fields at a time. Now how could I type on one text field and make the other twin text field have the same values simultaneously?
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
<script>
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..."/>' + '<br>' + '</div>' + '</div>');
$(OuterWrapper).append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '">' + '</div>');
x++;
return false;
});
});
</script>
I created a fiddle that I think does what you want: http://jsfiddle.net/3h1h5j7y/
Here is the code.
HTML
<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<div id="OuterWrapper"></div>
JavaScript
I added a data- attribute to the inputs with the tfCont id so that they can operate in pairs as they are added.
Also, I am using the on() method so that objects can be added dynamically. It is filtering on the fTypex class.
$(document).ready(function() {
var tfCont = 0;
var InputsWrapper = $("#InputsWrapper");
var x = InputsWrapper.length;
var namefield = $("#tfButton");
$(namefield).click(function() {
tfCont++;
$(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Thought of the day..." data-tfcount="' + tfCont + '"/>' + '<br>' + '</div>' + '</div>');
$("#OuterWrapper").append('<div id="textLayer_' + tfCont + '">' + '<input type="textarea" id="tf_' + tfCont + '" data-tfcount="' + tfCont + '">' + '</div>');
x++;
return false;
});
$(document).on("click blur keyup", "input.fTypex", function() {
var tfc = $(this).data("tfcount");
$("#tf_" + tfc).val(this.value);
});
});
I had to change $(OuterWrapper) from your example to $("#OuterWrapper") because there was not a variable.
Try something like this :
use onkeyup to call a function which binds the values
HTML
<body>
<input id='ip1' onkeyup='updateOther(this);' type='text'>
<input id='ip2' type='text'>
<script src="script.js"></script>
</body>
JS:
function updateOther(obj){
$('#ip2').val($(obj).val()) ;
}
http://plnkr.co/edit/dpwav5fGcisZcjBIzYyz?p=preview