How to execute javascript methods generated in html onlclick events - javascript

The updateValue() method isn't firing and I'm not sure how to even debug this using the browser.
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue(someTextData);\" /></td>");
}
function updateValue(newText) {
alert(newText);
}

The generated html is the problem. It cannot reference a variable in the scope of the generateHtmlTableRow function. So it will work:
function generateHtmlTableRow() {
var tr = $("<tr></tr>");
$("#results").append(tr);
var someTextData = "test";
tr.append("<td><input type=\"button\" value=\"TestButton\" onclick=\"updateValue('" + someTextData + "');\" /></td>");
}
function updateValue(newText) {
alert(newText);
}
$(document).ready(function(){
console.log('log');
generateHtmlTableRow();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results"></div>

An elegant way to do this is to
Store the someData values in HTML5 data- attributes when you create the <tr>. jQuery has the .data() function for this purpose.
Use a delegated event handler that catches all button clicks inside the <table>. The event handler can then retrieve the data again easily.
function generateTableRow(someData) {
$("<tr><td><button class='test'>TestButton</button></td></tr>")
.data("value", someData)
.appendTo("#results");
}
$(function(){
$("#results").on("click", "button.test", function () {
var value = $(this).closest("tr").data("value");
alert(value);
});
generateTableRow("test 1");
generateTableRow("test 2");
generateTableRow("test 3");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="results"></table>

Related

Onclick cannot find function to execute

I am using an onclick() function to add an item to cart.
<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(<?php echo $id;?>)'><span class='glyphicon glyphicon-shopping-cart'></span></button>
This is the js:
$(document).ready(function(){
var cart = [];
var id = $("#itemId").text();
var stockAvailable = $("itemStock").text();
var inCart = false;
function addToCart(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
}
}
However, I get the following error in the console upon clicking the button:
ReferenceError: addToCart is not defined
I have written the js code on a separate file and inluded it in the head section.
What could be the problem here
You cannot use addToCart without defining it.
You can define it in the place where you want to use this function.
$(document).ready(function() {
function addToCart(item) {
console.log('added');
}
});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Right way
function addToCart(item) {
console.log('added');
}
$(document).ready(function() {
});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
from the official jquery docs. https://learn.jquery.com/using-jquery-core/document-ready/
TLDR: document.ready runs only once so define your function outside of it.
Here i am showing you very basic example code based on your question
var id, cart = [], stockAvailable, inCart = false;
$(document).ready(function(){
id = $("#itemId").text();
stockAvailable = $("itemStock").text();
});
function addToCart(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
inCart = true;
console.log("item added in cart");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(1)'><span class='glyphicon glyphicon-shopping-cart'></span> Add to Cart</button>
Anyways you are using Jquery, so can you please check with jquery event handler.
Please find the answer using jquery click event.
$("#cartBtn").on("click", function(item){
id = item;
if (inCart == true){
console.log("item already in cart");
}
else{
cart.push(id);
}
}
})

Can't call jQuery function

I have a problem with my code.
I want to call a function but it's not working.
First, function show() displays button. This button has id='send' and it's inside the div with class='messagebox'. I want to call function on button click.
(I call function show in php script)
echo<<<ENDL
<div class="friendslistimgbox" onclick="show('$id','$login','$photo')">....</div>
ENDL;
$(.messagebox #send) or $(.messagebox > #send) are not working
$(document).ready(function(){
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
var data = JSON.parse(e.data);
var row = data.from+": "+data.msg+"<br/>";
$("#chats").append(row);
};
$(".messagebox #send").click(function(){
var userId = $("#userId").val();
var msg = $("#msg").val();
var data = {
userId: userId,
msg: msg
};
conn.send(JSON.stringify(data));
})
})
function show(id,login,photo){
$('.messagebox').html("<input type='hidden' id='userId' value='"+login+"'><input type='text' id='msg' class='sendmessage'><button id='send' type='submit' class='button_sendmessage'><i class='icon-right-dir'></i></button>");
$('#message_to').html("<a href='"+login+"'><img src='../userphotos/"+photo+"'>"+login+"</a>");
$("#allmessagesbox").css("visibility","visible");
}
HTML /
<div class="allmessagesbox" id="allmessagesbox">
<div class="messages">
<div class="message_to" id="message_to"></div>
</div>
<div class="messagebox"></div>
</div>
<div id="chats"></div>
You'll need to use the .on() method to register events with DOM elements that are dynamic (ie like your button, which might exist in the future).
In the case of your code, you can use on() in the following way:
// Replace this line:
// $(".messagebox #send").click(function(){
// With this:
$("body").on("click", ".messagebox #send", function(){
var userId = $("#userId").val();
var msg = $("#msg").val();
var data = {
userId: userId,
msg: msg
};
conn.send(JSON.stringify(data));
})
This can basically be read and understood as:
// For any dynamic element in scope or child of the body
$("body")
// Register a click event with any element that matches the
// .messagebox #send selector either now, or in the future
.on("click", ".messagebox #send", function(){
...
}));
For more information on on(), see the jQuery documentation

Nested quotes in javascript and html

I have a big problem with quotes in java script and html dom.
I want to use just double quotes("), not ' at all!
Here is my code:
<a onclick="aClicked("<span onclick="spanClicked("You clicked me")">I'm an Span</span>")">Add span</a>
<script type="text/javascript">
function aClicked(str) {
$(document).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>
Can anyone help throw kind of these problems!?
Tanks.
here is my original code (it work correctly but I just want to simplfy it and underestand it):
"I call this function with ajax"
<?php
function getTags() {
$values = ['test1', 'test2'];
$valuesString = '';
$baseSpanString = '<span><span class="tag">?</span><a onclick="Tags.Update($(this).parent().parent(), $(this).parent(), "tag");">x</a></span>';
foreach ($values as $tmpValue) {
if(trim($tmpValue) == '') {
continue;
}
$valuesString .= str_replace('?', $tmpValue, $baseSpanString);
}
$xhtml = '
<div>
<input type="text" onkeydown="return Tags.Insert($(this).parent(), $(this), event, \''.str_replace('"', '\\\'', $baseSpanString).'\', \'tag\');"/>
<textarea style="display:none;">'.implode('-', $values).'</textarea>
'.$valuesString.'
</div>
';
return $xhtml;
}
?>
<script type="text/javascript">
Tags = {};
Tags.Update = function(div, span, tagClass) {
div = $(div);
if(!div.length) {
alert('Error');
return false;
}
$(span).remove();
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
};
Tags.Insert = function(div, input, event, baseSpanString, tagClass) {
if (event.keyCode == 13)
{
div = $(div);
input = $(input);
if(!div.length || !input.length) {
alert('Error');
return false;
}
var val = input.val();
if(val && val != '') {
input.val('');
var spanString = baseSpanString.replace('?', val);
div.append(spanString);
}
var tagsSpan = $('.'+tagClass, div);
var tagsString = [];
if(tagsSpan.length) {
$.each(tagsSpan, function(index, val) {
tagsString.push($(val).text());
});
}
$('textarea', div).text(tagsString.join('-'));
return false;
}
};
</script>
Two answers:
Your string question
The right way instead
Your string question
' is the feature specifically designed for this. But sometimes this stuff does legitimately come up...
The key is to be aware of what kind of text you're dealing with at each stage:
Within the " of the attribute (onclick="..."), you're writing HTML text, even though what you're writing in that HTML text is JavaScript. So you can use " for quotes if you insist on not using '.
If you need to use a string within your JavaScript code (such as the onclick in the string we're passing aClicked) and insist on not using ', put a \ before the ".
If you need to use a quote within an HTML string within an HTML string (such as the string being passed to spanClicked, which is an HTML string inside a JavaScript string inside an HTML string), then you need something that will end up being " after the entities in the first HTML string are processed. So that's &quot;
So:
<a onclick="aClicked("<span onclick=\"spanClicked(&quot;You clicked me&quot;)\">I'm an Span</span>")">Add span</a>
Example:
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
<a onclick="aClicked("<span onclick=\"spanClicked(&quot;You clicked me&quot;)\">I'm an Span</span>")">Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The right way instead
But again, this is all just a way to make your code complicated unmaintainable; instead, just use jQuery, as you're already using jQuery:
Example:
$("a").on("click", function() {
var span = $("<span>I'm a span</span>");
span.on("click", function() {
spanClicked("You clicked me");
});
$(document.body).append(span);
});
function spanClicked(str) {
alert(str);
}
<a>Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you are using jQuery use unobtrusive event handlers, for this .on() method can be used. When generating elements dynamically you need to use Event Delegation.
I would also recommend you to use semantically correct elements, thus used <button> element
$("#addSpan").on("click", function() {
$('#container').append("<span class=\"myspan\">I'm an Span</span><br/>");
})
$("#container").on("click", ".myspan", function() {
console.log("You clicked me");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="addSpan">Add span</button>
<div id="container">
</div>
Better make it as a function like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="adds();">Add span</a>
<script type="text/javascript">
function adds(){
aClicked("<span onclick='spanClicked(\"You clicked me\")'>I'm an Span</span>");
}
function aClicked(str) {
$(document.body).append(str);
}
function spanClicked(str) {
alert(str);
}
</script>

Unable to call JS function from onclick event

I am trying to call a JavaScript function from the onclick event of two different buttons. I have dug around and searched for like problems but have not found a solutions. When I click either button I get the error
Error: 'RemoveCode' is undefined'
What am I doing wrong?
<script type="text/javascript">
$(document).ready(function ()
{
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
});
</script>
Code for my buttons:
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select> <button class="removeButton" onclick="RemoveCode('Project')" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select> <button class="removeButton" onclick="RemoveCode('Task')" type="button">-</button>
</li>
I should note that on the same page there are multiple change events for the other elements on the page and they all work fine. It is just this `onclickP that is failing.
Firstly note that in your if condition you need to use == (not =) to compare values.
To solve your issue you have two options. Firstly you could simply move the RemoveCode function out of the scope of the document.ready handler so that it can be accessed from the onclick attribute:
<script type="text/javascript">
function RemoveCode(codeType)
{
// your code...
}
$(document).ready(function ()
{
// your code...
});
</script>
Alternatively, it would be much better practice to add your event handlers using unobtrusive Javascript. As you're using jQuery, here's how you can do that:
$(function() {
$('button').click(function() {
var $selectedProjectsField = $("#SelectedProjects");
var $selectedProjectCodesField = $("#SelectedProjectCodes");
var $selectedTasksField = $("#SelectedTasks");
var $selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if ($(this).data('codetype') == "Project") {
selectedOption = $selectedProjectsField.find(':selected').index();
} else {
selectedOption = $selectedTasksField.find(':selected').index();
}
alert(selectedOption);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<label for="SelectedProjects">Selected Projects:</label>
<select size="1" id="SelectedProjects" name="SelectedProjects" multiple></select>
<button class="removeButton" data-codetype="Project" type="button">-</button>
</li>
<li>
<label for="SelectedTasks">Selected Tasks:</label>
<select size="1" multiple id="SelectedTasks" name="SelectedTasks"></select>
<button class="removeButton" data-codetype="Task" type="button">-</button>
</li>
</ul>
You are defining your RemoveCode method inside a closure. This function will thus not be available as onclick callbacks of your HTML elements.
You can just update your code to this and it should work:
<script type="text/javascript">
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
put your function out side of document.ready()
<script type="text/javascript">
$(document).ready(function () // No Need of this Function here
{ });
function RemoveCode(codeType) // Automatically load when Your page is getting loaded on Browser.
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOption;
if (codeType = "Project")
{
selectedOption = $("#SelectedProjects :selected").index();
}
else
{
selectedOption = $("#SelectedTasks :selected").index();
}
alert(selectedOption);
}
</script>
You are defining your ready() method inside of a closure.
You then have two approaches you can use. First is you can not use $(document).ready() as the buttons that call ready() can't be clicked until the document is ready anyway.
Second is you could bind the onclick inside of your $(document).ready().
$(document).ready(function() {
$('#firstItem').click(function() { Ready('Project'); });
....
});

Javascript results to div

Q1: My point is create many buttons as many rows of array. Like this, only one button appears.
<script type="text/javascript">
var myArray = [];
$('#button').click(function(){
var value1 = $('#value1').val();
var value2 = $('#value1').val();
var value3 = $('#value1').val();
var newArray = [];
var newArray[0] = value1;
var newArray[1] = value2;
var newArray[2] = value3;
myArray.push(newArray);
$("#save").append(
$("<button>").click(function() {
myFunction.apply(null, myArray);
}).text("Click me!")
);
});
});
function myFunction(value1,value2,value3)
{
var jsonData = $.ajax({
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3
dataType: "json",
async: false
}).responseText;
(...)
}
//edited: problem maybe found. I said buttons dont do anything because of this.
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined
//it seems that value1 gets all values :s
</script>
<div id ="save"></div>
Im looking for a solution that return someting like this:
eg:
<!--<button onclick="myFunction(name,age,country)">Click me</button>-->
<button onclick="myFunction(paul,23,USA)">Click me</button>
<button onclick="myFunction(john,23,USA)">Click me</button>
EDITED MY CODE WITH MORE DETAILS
.html replaces, and your quotes are mismatched. But it doesn't matter - jQuery is better at manipulating the DOM than it is at manipulating strings. Try:
$("#save").append(
$.map(myArray, function(item) {
return $("<button>").click(function() {
myFunction.apply(null, item);
}).text("Click me");
})
);
Here's a demo.
You're only seeing one button because the .html() method replaces the html of the element. It doesn't append.
Luckily, jQuery has a method for the behavior you want, fittingly called append. Change it to look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>");
$("#save").append(button) ;
}
I intentionally left the onclick behavior out of that snippet. You can write it in the html of the button you create, as you have been, or you can do it with jQuery - the second method is preferable, and would look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>")
.click(function(){
// call the actual function you want called here
});
$("#save").append(button);
}
Did you mean this:
<div id="save">
</div>
<script type="text/javascript">
function addButtons(){
for(i=0;i<myArray.length;i++)
{
var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>')
$(button).data('details',myArray[i]).appendTo("#save");
}
}
function myFunction(element){
alert($(element).data('details'));
}
</script>
This is because you are replacing the html in the $("#save") in the loop . Try
$("#save").append("<button onclick="myFunction('"+myArray[i]+"')">Click me</button>") ;
for(i=0;i<myArray.length;i++){
//Create a new DOM button element ( as jQuery object )
// Set the current button index, and add the click action
var button = $('<button />').data('myindex', i).click(function(){
var myArrayItem = myArray[$(this).data('myindex')];
alert(myArrayItem);
}).html('My label n. '+i);
$('#save').append(button)
}
Why bothering with all the JQuery and complicated code, just use simple way to implement this
<script type="text/javascript" >
var myArray = ["New York", "Boston", "San Jose", "Los Angeles"];
var strHTML = "";
for(i=0;i<myArray.length;i++)
{
strHTML += "<button onclick='myFunction("+i+")'>Click me</button>";
}
$("#save").innerHTML = strHTML;
function myFunction(index)
{
alert(index);
// do your logic here with index
}
</script>

Categories

Resources