showhide function in dynamically created form does not work - javascript

I'm developing a webpage with a form that is created dynamically by means of javascript (jquery). For each (repetitive) set of form elements a Show/hide function is added to show and hide the elements, and I dont get this show/hide code working - I suspect the error is located as indicated within the code below, and I think I struggle to put the quotes at the right place (?) The console indicates an error "Uncaught SyntaxError: Unexpected token } " which I dont understand; when excluding the suspected erroneous line there are no further errors and I dont see where this '}' shows up where it's not supposed to show up.
Javascript code:
function ShowHide(id) {
$(id).toggle();
}
$(document).ready(function () {
var buildform = function () {
var form ='<div id="form">'
for (var i = 0; i < 2; i++) {
form += '<div id="filename"' + i + '> Document </div> </td>';
//error in next line (?)
form += '<button onclick="ShowHide(\'#filename'+ i +'\')"> Show/hide document </button> </td> </tr>';
} //for i
form += '</div>'; //id="form"
console.log('FORM: '+form);
return
} //buildform()
$("#wrapper").append(form);
}); //$(document).
HTML code:
<div id="wrapper"></div>
Output by javaconsole():
<div id="form"><div id="filename"0> Document </div><button onclick="ShowHide('#filename0')"> Show/hide document </button></div><div id="filename"1> Document </div><button onclick="ShowHide('#filename1')"> Show/hide document </button></div>

You're quotes are wrong.
form += '<td> <button onclick="ShowHide(\'#filename'+ i + '\')"> Show/hide document </button> </td> </tr>';
I matched the quotes in parenthesis, and escaped them with \. Also, you're saving your created html, but never show anywhere that it would actually output the html to the page. You need to actually output the information created. For example:
The HTML:
<div ="outputContainer"></div>
Inside your function:
$("#outputContainer").html(form);

Escape the quotes correct
Please change the line:
form += '<td> <button onclick="ShowHide("#filename'+ i +')"> Show/hide document </button> </td> </tr>';
to this:
form += '<td> <button onclick="ShowHide(\'#filename'+ i +'\')"> Show/hide document </button> </td> </tr>';
^ ^

Related

Jquery command not executing, can't see what I'm doing wrong

Im trying to access random quotes through an API using Jquery. I am very new to this so I'm sure there is a simple solution that I cannot see. Basically this is my HTML code:
<div class="col-md-6">
<button id="quoteClick" type="button" class="btn btn-success btn-lg quoteButton text-center btn-block">Get Quote</button>
</div>
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8 show boxed text-center">
Text
</div>
<div class="col-md-2">
</div>
</div>
My JS is this:
$(document).ready(function() {
$("#quoteClick").on("click", function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
json.forEach(function(x) {
html += "<div class = 'quote'>";
html += "<h3 '" + x.quoteText + "' "+ "'>";
html += "</div>";
});
     $(".show").html(html);
});
});
});
When I use console.log(json) I can print the object I'm querying from, but when I actually try to fish out a quote and print it on my web page nothing happens. I am using codepen.
You shouldn't be iterating over the object you get from the API. If you look at a single API call, one result I got looked like this:
{
"quoteText": "To be thoughtful and kind only takes a few seconds compared to the timeless hurt caused by one rude gesture.",
"quoteAuthor": "Byron Pulsifer",
"senderName": "",
"senderLink": "",
"quoteLink": "http:\/\/forismatic.com\/en\/4255d6ba93\/"
}
You just need to drop the forEach call, and your code will work.
Also (gavgrif noted this first in their answer), your HTML is malformed - you should have the text inside the h3.
This should be better:
$(document).ready(function() {
$("#quoteClick").click(function() {
$.getJSON("https://crossorigin.me/http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
var html = "";
html += "<div class = 'quote'>";
html += "<h3>" + json.quoteText + "</h3>";
html += "</div>";
$(".show").html(html);
});
});
});

Run function on dynamic html

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

how to add a unique id to a onclick event

I am having some code between pre tags and I want to catch al that code with an onclick event
My html structure is like below:
<div class="Message">
<div class="surroundpre">
<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span>
<pre class="CodeBlock id="id22015640">
<!-- code goes her -->
</pre>
</div>
</div>
The pre elements and the div with class surroundpre is created by javascript.
The unique id for the pre:
$('pre').each(function(){
if ($(this).attr('id') == undefined){
$(this).attr('id','id'+Math.floor((Math.random() * 99999999) + 1))
}
});
The div with surroundpre is created like below:
$('.Message .CodeBlock', this).wrap('<div class=surroundpre></div>');
The span is created with php variable:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span><br />';
in combination with:
$('.surroundpre').prepend('$SelectButton');
My question: the id1 in the php variable should be replaced with the same unique id as in the pre tag.
How can I achieve this?
Or is there an other method to achieve this?
This might work for you, make a few changes, first in PHP:
$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, this.getAttribute(\"data-block-id\"))">[Select and Copy]</span><br />';
Then in JS:
$('pre').each(function(){
var id;
if ($(this).attr('id') == undefined){
id = 'id'+Math.floor((Math.random() * 99999999) + 1);
$(this).attr('id',id);
$(this).prev('span').attr('data-block-id',id);
}
});
Now the id generated in js is attached to the span at the same time of creation, when it is available to you, and the pregenerated (in PHP) onclick event can access it when it needs it (as long as that is after the ID setting code has run).

Error passing json array onclick- html and javascript

I am generating a clickable list dynamically using jquery. here is the code that generates the list.
for(dayint=0;dayint < day_arr.length;dayint++){
var temp_pass = JSON.stringify(day_arr[dayint]);
//alert(temp_pass);
$("#itin_list").append('<b>Day '+ dayint + ' of Trip from '+ start_n +' to '+ end_n +' </b> <button data-toggle="modal" data-target="#dirModal" style="position:absolute;bottom:5px; right:5px;float:right" class="btn btn-primary">Show Directions</button><br>');
}
The problem I have is when passing the json array to my sethidddendiv function. The code sample for the function is as below:
window.sethiddendiv = function(str) {
//var nisal = $.parseJSON(str);
alert(str);
}
When the list item is clicked, instead of giving the json array, it alerts "undefined" all the time.
Here is the html that is generated in the page when I inspect element:
<b>Day 0 of Trip from Colombo to Kandy </b> <button data-toggle="modal" data-target="#dirModal" style="position:absolute;bottom:5px; right:5px;float:right" class="btn btn-primary">Show Directions</button>
What could be the issue here?
I already tried using single quotes for the onclick, but it didnt work. Any help would be very welcome. I'm stuck.

Using jQuery to create a number of input fields, based on value entered

I have a form in which I ask the user how many file inputs they need, and I'd like to generate the suitable number of file browsing inputs dynamically based on the answer.
Here is my attempt:
$("#howmany").change(function()
{
var htmlString = "";
var len = $(this).val();
for (var i = 0; i <= len; i++)
{
htmlString += "
<tr>
<td>
<input name="ufile[]" type="file" id="ufile[]" size="50" />
</td>
</tr>
";
}
$("#dynamic_upload").html(htmlString);
}
HTML
<input id="howmany" />
<table id="dynamic_upload">
</table>
The idea being that repeating "units" of inputs will be generated based on the number entered.
But it isn't working, any idea where I'm going wrong?
EDIT: More clarity on "it isn't working" (apologies). When I include this code, after entering the number into the field "howmany" there is no visable reaction. No error messages appear, although - is there an error log somewhere I don't know how to read? (new to this)
It's not possible to create a string like that. Try:
htmlString += "<tr>";
htmlString += "<td>";
htmlString += '<input name="ufile[]" type="file" id="ufile[]" size="50" />';
htmlString += "</td>";
htmlString += "</tr>";
Also remember you need to use single quotes around the string if it contains double quotes, or escape them.
You are also missing ); from the end of the function:
$("#dynamic_upload").html(htmlString);
} <--- this should be });
You can't have newlines in JavaScript strings. Moreover, you are using double-quotes within the string (i.e. for the <input> attributes). Possible rewrite:
htmlString += '<tr><td><input name="ufile[]" type="file" id="ufile[]" size="50"></td></tr>';
In the future, please give a more descriptive problem than "it isn't working" -- for example, do you get any error messages?

Categories

Resources