Firing code on load of page not working - javascript

I have this code tied to a button that when clicked, executes code to hide a table row:
<script>
$(function hideinstr() {
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
});
</script>
I would like this code to execute by default when the page loads, and let the user click the button if the want to reveal the table row. How can I do this when the 'click' is built right into this code?

Your solution never executes the function hideinstr(). Also, consider using $(document).ready if your code is executed in the <head>. Add extra parentheses to execute the function, or remove the surrounding function (function hideinstr).
<script>
$(document).ready(function hideinstr() {
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
}());
</script>
or
<script>
$(document).ready(
$('tr.parent td').on("click", "input.instr", function () {
var idOfParent = $(this).parents('tr').attr('id');
$('tr.child-' + idOfParent).toggle('slow');
});
);
</script>
And to execute the event script directly, use $('tr.parent td').click();.

Related

Javascript change event never called

I have this order question related top javascript. In the aspx page I have this SubmissionMaintenance.init that call this return classes in javascript getRecord and saveRecord. I wanted to add a $("#ddlCompany").change event and no matter when I add it it will never get called.
aspx Page
<script type="text/javascript">
$(document).ready(function () {
SubmissionMaintenance.init();
});
JS Page
return {
init: function () {
getRecord();
saveRecord();
}
}
var getRecord = function () {
html += "<select class='form-control select2-multiple' multiple='multiple' id='ddlCompany' name='ddlCompany' >";
$("#submission").html(html);
}
You'll need to add the change event listener to a parent element because the element you want to listen to is added after the dom has loaded.
Try this:
$( "#submission" ).on( "change", "#ddlCompany", function() {
console.log( '#ddlCompany change' );
});

Execute a function when pressing a button in jQuery

I am quite new to programming, and have met a problem.
I really want to run this function, when I press a button. Here is the function that I want to run:
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
Alright, I want to run this function, when pressing a button, and here is the code for my jQuery button:
$(document).ready(function(){
$('button').click(function() {
//run function here
});
});
It doesn't have to be jQuery, I just thought that would be easier. I would be very grateful if somebody would help and explain.
Thanks in advance.
Inside your HTML, you can use the onclick event handler to call a function when the button is clicked, using vanilla javascript. Like so:
<button onclick="generateTip()">button text</button>
If you want a solution using jQuery and your current code, all you have to do is call the generateTip() function inside the $('button').click wrapper:
$(document).ready(function(){
$('button').click(function() {
generateTip();
});
});
So if you have a .js file with this code:
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
You can then attach it to an HTML element like so:
<button onclick="generateTip()"> Button </button>
Hope that helps
You're already there?
JQUERY Script:
<script>
$(document).ready(function(){
$('button').click(function() {
generateTip();
});
});
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
}
</script>
or by onclick only in the actual HTML and a script above:
<script>
function generateTip() {
var tip = tipsList[generateNumber()];
var tipElement = document.querySelector('.js-tip');
tipElement.innerHTML = tip;
</script>
Then in your HTML something like this
<input type="button" name"button" onclick="generateTip()";
To execute the function generateTip() on click, put this in your button code:
<input type="button" name="any" onclick="generateTip()"/>

JavaScript button event handler not working

I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.
HTML
<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>
Javascript
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
You have a couple of issues here:
Issue #1:
The element does not exist in the DOM to bind to yet, so do any or all of the following:
Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
Use event delegation to bind to events on future elements.
Put all the JavaScript in the ready handler.
Issue #2:
You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.
See the HTML5 spec for button for reference:
Content model:
Phrasing content, but there must be no interactive content descendant.
Instead, bind the click event handler to the button itself.
// Variables
var waarde = {
amount: 2
};
$(document).ready(function(){
updateValues();
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button"><span id="click">0</span></button>
Also, unless you need the span element for something else, you could get rid of it and just use:
document.getElementById("button").innerHTML = waarde.amount;
You should put this code:
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..
You have to write "Click" event in document.ready
var waarde = {
amount: 2
};
$(document).ready(function () {
$('#click').click(function () {
waarde.amount = waarde.amount + 1;
updateValues();
});
updateValues();
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
The problem with your code is you are not assigning an event handler when javascript loads the js file. It should be called in the ready function.
var waarde = {
amount:2
};
$(document).ready(function(){
$('#click').click(function(){
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues(){
document.getElementById("click").innerHTML = waarde.amount;
}
You should wrap it inside the ready method!
// Variables
var waarde = {
amount:2
};
$(document).ready(function() {
$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});
});
function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}
Here's a codepen link http://codepen.io/anon/pen/vKXQza
Two points:
You should put your jQuery event listener inside the document.ready.
There is no guarantee to work click event on span.
// Variables
var waarde = {
amount:2
};
$(document).ready(function(){
updateValues();
$('#click2').click(function(){
waarde.amount++;
updateValues();
});
});
function updateValues(){
document.getElementById("click2").innerHTML = waarde.amount;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<button id="click2">0</button>
You can see your problem solution is here
You are missing button click event in $(document).ready(function(){}(;

Calling javascript function

I have the problem, that my javascript function isnĀ“t when I press the button:
<script type="text/javascript" language="javascript">
(function ($) {
$.fn.addToList = function (opts) {
var input = $(this);
opts.button.click(function () {
opts.list.append("<li>" + input.val() + "</li>");
});
};
}(window.jQuery));
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
</script>
and
<input type="text" id="zutat" name="zutat"></input>
<input type="button" id="btn" value="Click">
<ul id="list"></ul>
How do I call this javascript function? What is my problem?
If your script tag is before the #zutat" stuff, then you are trying to manipulate on #zutat when the DOM elements are not ready yet. In this case, When the jQuery selector is being executed, it will not match the elements, since they are not available yet.
To fix it, you should wrap your codes by the $(document).ready function or put it at the bottom of body tag.
<script type="text/javascript" language="javascript">
(function($) {
$.fn.addToList = function(opts) {
var input = $(this);
opts.button.click(function() {
opts.list.append("<li>" + input.val() + "</li>");
});
};
$(document).ready(function() { // <<<<<<< execute after document ready.
$("#zutat").addToList({
button: $("#btn"),
list: $("#list")
});
});
})(window.jQuery);
</script>
I think you should move the parenthesis this way
})(window.jQuery);
In Firefox (I am using Firebug to test this) if you do this
function(){ alert("GONG"); }();
It gives you an error but if you wrap the function with parenthesis
(function(){ alert("GONG"); })();
The anonymous function will be executed.
You should also wrap the call to the dom elements in a $(document).ready(); call as showed in qiao's answer.
if you want to add <li>s to a <ul> when you click a button, you are going about it in a very round about way. you don't need to extend jquery or object prototype to do that.
try the following
$("#button").click(function() {
var val = $("zutat").val();
$("#list").append($("<li>" + val + "</li>"));
});
Normally the click event is handled like this
$('#btn').on("click",function(){
// code
});
I don't know what your code does exactly but not that what you want.

jQuery - Dynamically Create Button and Attach Event Handler

I would like to dynamically add a button control to a table using jQuery and attach a click event handler. I tried the following, without success:
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before('<tr><td>' + test.html() + '</td></tr>');
});
The above code successfully adds a new row, but it doesn't handle adding the button correctly. How would I accomplish this using jQuery?
Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
});
var parent = $('<tr><td></td></tr>').children().append(test).end();
$("#addNodeTable tr:last").before(parent);
});
Or,
$("#myButton").click(function ()
{
var test = $('<button/>',
{
text: 'Test',
click: function () { alert('hi'); }
}).wrap('<tr><td></td></tr>').closest('tr');
$("#addNodeTable tr:last").before(test);
});
If you don't like passing a map of properties to $(), you can instead use
$('<button/>')
.text('Test')
.click(function () { alert('hi'); });
// or
$('<button>Test</button>').click(function () { alert('hi'); });
Quick fix.
Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.
$("#myButton").click(function () {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed
var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
var td = $('<td>').append(test).appendTo(tr);
});
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.
You were just adding the html string. Not the element you created with a click event listener.
Try This:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
<table id="addNodeTable">
<tr>
<td>
Row 1
</td>
</tr>
<tr >
<td>
Row 2
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
var test = $('<button>Test</button>').click(function () {
alert('hi');
});
$("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);
});
</script>

Categories