I have a script that creates some html for products. In the static way this html have onclick events. However this doesn't work when I create the html dynamically. The onclick event fires a function for a quantity box with "+" and "-" symbols.
How do I make it so that it works with dynamic content? I've searched the forum but can not come with a solution. I prefer to somehow keep the function updateQuantity but have it work with both dynamic and static content.
Any help greatly appreciated.
Console now returns errors saying that up and down are not defined.
My script (I have beautified the code for readabillity)
$.getJSON(url, function(json){
......
$.each(json.products, function(index, product){
.....
productHtml += '<div class="item-btn" data-p-vid="'+product.vid+'">
<form action="" id="product_configure_form2" method="post" role="form">
<div class="custom-quantity-input">
<input type="text" name="quantity" value="1">
+
-
</div>
</form>
</div>';
function updateQuantity(item, way){
var inputField = $(item).closest('.custom-quantity-input').find('input');
var quantity = parseInt(inputField.val(), 10);
if (way == 'up'){
if (quantity < 10000){
quantity++;
} else {
quantity = 10000;
}
} else {
if (quantity > 1){
quantity--;
} else {
quantity = 1;
}
}
inputField.val(quantity);
}
Best practices suggests event delegation.
Something like this also avoids your issue with nested single quotes:
$(function() {
$("#productHTMLContainer").on("click",".up, .down, .item-add-btn-cart",function(e) {
e.preventDefault();
updateQuantity(this,$(this).hasClass("up")?"up":"down");
});
});
where productHTMLContainer is whatever you insert the productHtml into.
It also seems you are not consistent with your html:
+
-
should it not be
+
-
???
up and down are considered variables because you aren't escaping the quotes and your html string is wrapped with quotes.
This should work :
productHtml +=
'<div class="item-btn" data-p-vid="'+product.vid+'">
<form action="" id="product_configure_form2" method="post" role="form">
<div class="custom-quantity-input">
<input type="text" name="quantity" value="1">
+
-
</div>
</form>
</div>';
try to change updateQuantity(this,'down') to updateQuantity(this,\'down\')
Hint: You use "'" as string delimiter, so, if you want to use symbol "'" inside this string you must escape them
you can use $(document) in jQuery to attach the events to the document and not to the especific element.. follow the example:
$(document).on('click','.item-add-btn-cart', function(e){
//run updateQuantity() here
})
Important using .on to attach the event in this case. So if you create dinamically html this event will keep working
Related
I have this function :
<script>
function f(id){
return $("#" + id).val();
}
</script>
And this html's tag:
<input id=f(#payMethod) type="radio" value=" #method.Value" name="cartaCont" />
My id is buildered with a foreach that pass value to variable:
string payMethod = "payMethod";
payMethod += method.Text;
My question is: Is correct Call this index in an other function in this way ?? :
function() {
$('input[id ^= #PayMethod]').attr('checked', headerChecked);
}
thanks for feedback
It seems that you want to write some html and javascript code, relating to each item of a list.
In this case, I often prefer to directly write html and related javascript for event binding and code customization.
I supposing that method is your razor variable in your foreach, and methods is the enumerable variable to loop, you may would write this code for html
#foreach(var method in methods)
{
// this is C#, not javascript
// replacing spaces to build right id code for html
string payMethod = "payMethod" + method.Value.Replace(" ", "");
<text>
<input id="#payMethod" class="payMethodRadio" type="radio" value="#method.Value" name="cartaCont" />
<script>
$(document).ready(function () {
$("##payMethod").on('change', function (e) {
/* here if you want to write some javascript events for each item related to its html ID, for example change event */
});
});
</script>
</text>
}
But if you want to write some common jQuery code for this set of radio buttons, I' prefer to manage it with class selector rather than ID rules, as follow
function() {
$('payMethodRadio')...
}
Hope this, help you for better code management.
Br
Andryx
Try to add Onchange event to input.Here is a demo code:
#{var payMethod = 0;}
#foreach (var method in Model.Methods)
{
<input id="#payMethod" type="radio" value=" #method.Value" name="cartaCont" onchange="Add(#payMethod)"/>
payMethod++;
}
js:
function Add(id) {
$('#'+id).attr('checked', headerChecked);
}
im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.
Although the question title gives an impression that I want to ask one question, but there are two problems I have facing at the moment.
I have gone through few similar questions on how to clear the input text area on button click, but most of them are for fixed input class or id's.
Problem 1: I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
Problem 2: After entering individual values in the betslip input boxes and if I click "clear all" button. It should clear all the inputs entered earlier in the bet slip.
Here is the HTML structure
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field - This is where I am creating the input fields
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text" class="betInput"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
HTML for Apply to all and Clear all button
APPLY TO ALL <input type="text">
CLEAR ALL
JS where I need to implement those 2 functions
function applyToAllBetInput() {
$('.apply').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
}
function clearAllBetInput() {
$('.clearall').click(function() {
$('div.bet').find('input').val('');
});
}
The best thing to do is remove the inline event handlers from the links, like this...
APPLY TO ALL <input type="text">
CLEAR ALL
Then, assign the event handlers in your script...
$("a.button.apply").on("click", function(e) {
e.preventDefault();
applyToAllBetInput($(this).find("input").val());
});
$("a.button.clearall").on("click", function(e) {
e.preventDefault();
applyToAllBetInput("");
});
And this would apply the value to all inputs...
function applyToAllBetInput(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
If you pass a parameter into applyToAllBetInput and then set the inputs with that then you only need the one function, as they both do the same thing, but with different values. Best to only have 1 bit of code if it's only doing 1 thing, then you only have to fix it once if things change in the future :)
Please replace the id's i've given with your actual button/textarea ids (give ID's to your elements).
$('#txtApplyToAll').change(function() {
$(this).prevAll().find('input[type=text]').val($(this).val());
});
$('#btnClearAll').click(function() {
$('#txtApplyToAll').prevAll().find('input[type=text].val('');
});
There are several general suggestions I'd make before even starting to write the code. First, Why are you using longhand JavaScript when you have jQuery available? For example:
inputId = divId.document.getElementById('input');
should be simply:
inputId = $(inputId).find('input');
(or something along those lines--I'm not sure what you're after with that.)
Next, you're using inline click handlers. Instead, use event listeners:
<a href="javascript: applyToAllBetInput()" ...
Should be
$('a#my-id').click(function() { ... }
Finally, you can target all your inputs for clearing with a selector like this:
$('div.bet').find('input').val('');
is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>
I'm trying to input a form with Javascript. On the form, if the dropdown selection is a certain selection then specific form fields will appear below.
Here is the code I currently have, but it doesn't seem to work, I am guessing document.writeln is not the proper method. If I add an alert to see if it is pulling the selection it works, so something with adding the form in is failing. After the document.writeln the alert doesn't even come up anymore?
<script language="javascript">
var HelpTopic = document.getElementById('type');
HelpTopic.onchange=function() {
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.writeln('\<li\>
\<label for\=\"confirm\"\>Input name*\<\/label\>
\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>
\<\/li\>');
} else {
alert("Fails");
}
}
</script>
You can't span a string over multiple lines in JS. You need something like this:
document.writeln('\<li\>' +
'\<label for\=\"confirm\"\>Input name*\<\/label\>' +
'\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>' +
'\<\/li\>');
EDIT: You don't need so much escaping. This will work just as well:
document.writeln(
'<li>' +
'<label for="confirm">Input name*</label> ' +
'<input type="text" name="inputs" id="names" required />' +
'</li>');
To properly add list item to some list have such code instead:
var oList = document.getElementById("MyList");
var oItem = document.createElement("li");
oItem.innerHTML = "<label for='confirm'>Input name*</label><input type='text' name='inputs' required />";
oList.appendChild(oItem);
This will add item to list with ID MyList.
just a quick note, multi line strings are supported in javascript like this
'<li>\
<label for="confirm">Input name*</label>\
<input type="text" name="inputs" id="names" required />\
</li>'
I agree with Shadow Wizard, that would be the best way to append a list
The way you're trying to dynamically modify the "onChange" (missing capital C) seems to have trouble with Chrome
Also, you cant split a string over multiple lines the way you did
The following code should work, notice I added "onChange=myfunc();" to the select:
<select id=type onChange=myfunc();>";
<option value=Other>Other</option>
<option value=Analytics>Analytics</option>
</select>
<script language="javascript">
function myfunc()
{
var HelpTopic = document.getElementById('type');
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.write('<li><label for="confirm">Input name*</label><input type="text" name="inputs" id="names" required></li>');
} else {
alert("Fails");
}
}
</script>