I have a button
<button type="button" data-id="5" class="get_attr" >Click Me</button>
and i want to get the data-id value then i write the code
<script type="text/javascript">
$(".get_attr").on("click",function(){
var id = $(this).data("id");
console.log("id = "+id); //id = 5
});
</script>
Suppose I want this value, or do any functionality on this button from another function if i call function from this code like and I want like this:
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(this){ // it will take it as a parameter
var id = $(this).data("id");
console.log("id = "+id); //id = 5
}
</script>
You can not use 'this' becasue it is Javascript keyword
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(abc){ // it will take it as a parameter
var id = $(abc).data("id");
console.log("id = "+id); //id = 5
}
Now its work fine...
Being this is a reserved word, change the parameter name from this to some other like in updateValue(thatObj).
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(thatObj){
var id = $(thatObj).data("id");
console.log("id = "+id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-id="5" class="get_attr" >Click Me</button>
You cannot use a reserved keyword in your function definition. It should work with simply using another name in the definition.
<script type="text/javascript">
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(originalObject){ // it will take it as a parameter
var id = $(this).data("id");
console.log("id = "+id); //id = 5
}
</script>
Try this
$(".get_attr").on("click",function(){
var id = $(this).data("id");
console.log("id = "+id); //id = 5
});
$(".get_attr").on("click",function(){
updateValue(this);
});
function updateValue(x){ // it will take it as a parameter
var id = $(x).data("id");
console.log("id = "+id); //id = 5
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" data-id="5" class="get_attr" >Click Me</button>
Related
I'm just starting web development, and have a function loadTweets that pulls from another file and displays, and when I get rid of the button, and just run it directly as an anonymous function it works, however, for some reason the button does not work to call the function.
Any help would be greatly appreciated, thanks!
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
</head>
<button type = "button" onclick="loadTweets"> Load </button>
<body>
<script>
$(document).ready(function(){
var loadTweets = function(){
var $body = $('body');
$body.html('');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
}
});
// });
</script>
</body>
</html>
You need define the function outside the document-ready handler and to use () with function
<button type = "button" onclick="loadTweets()"> Load </button>
<script>
var loadTweets = function(){
//
});
</script>
However I would suggest you to use unobtrusive event handler.
HTML, Add an ID attribute to button
<button type="button" id="loadTweets"> Load </button>
Script, then use ID selector to target the element and .on() to bind event handler.
$(document).ready(function () {
var loadTweets = function () {
//existing code
}
$('#loadTweets').on('click', loadTweets)
});
You can use in another way
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
</head>
<body>
<button type = "button" onclick="loadTweets()"> Load </button>
<script>
function loadTweets(){
var $body = $('body');
$body.html('');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
}
</script>
</body>
</html>
I need to pass generated Random number from JS function to the html div, but its not able to pass it on,here is my code snippet
<html>
<head>
</head>
<body>
<button id="order" onclick="getRand()">orderId</button>
<div id="order_id"></div>
<script>
var getRand = function () {
var elem = Math.floor(Math.random() * 89999 + 10000);
document.getElementById("order_id").innerHTML = elem.value;
};
</script>
</body>
</html>
Try with this: Working example :
<html>
<body>
<head><h1>CRS</h1></head>
<button id= "order" onclick="getRand()">orderId</button>
<div id="order_id">ff</div>
<script>
var getRand = function() {
var elem = Math.floor(Math.random()*89999+10000);
document.getElementById("order_id").innerHTML = elem;
};
</script>
</body>
</html>
You just change elem.value to elem
Check This Answers it is working good
var getRand = function() {
var elem = Math.floor(Math.random()*89999+10000);
document.getElementById("order_id").innerHTML = elem;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id= "order" onclick="getRand()">orderId</button>
<div id="order_id">ff</div>
Trying to get the button called, "check" to show the var result from the answer prompt1 function. For whatever reason when I run the code nothing happens when the button is clicked. I know the calculation is right because, when I set the answer button to give the intended alert, it works properly. How do I get the second button to display my results entered?
<!DOCTYPE html>
<head>
<!--
Name: Dakota Trumbull
Date:
Class:
Purpose:
-->
<title>Math Test</title>
</head>
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
<p></p>
<p>Q2: 4 * 6 = ??</p>
<button id = "Q2A">Answer</button>
<button id = "Q2C">Check</button>
<p></p>
<p>Q3: 25 - 14 = ??</p>
<button id = "Q3A">Answer</button>
<button id = "Q3C">Check</button>
<p></p>
<p>Q4: 48 / 3 = ??</p>
<button id = "Q4A">Answer</button>
<button id = "Q4C">Check</button>
<p></p>
<p>Q5: 26 % 6 = ??</p>
<button id = "Q5A">Answer</button>
<button id = "Q5C">Check</button>
</body>
<script>
//Q1
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
var result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
</script>
</html>
result is declared in answerPrompt1, which gives it local scope (i.e. it isn't visible outside that function). move the declaration to just before the function:
var result = "You have not given an answer yet";
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: ");
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
<body>
<h1>Simple Math Test</h1>
<p>Q1: 5 + 9 = ??</p>
<button id = "Q1A" onclick = "answerPrompt1()">Answer</button>
<button id = "Q1C" onclick ="showResult()">Check</button>
</p>
</body>
You should change your result variable in a way that it can be accessible to both functions answerPrompt1() and showResult() You can have a clear understanding about how javascript scope works from here.
var result = "You have not given an answer yet"; //this variable is accessible to both functions
function answerPrompt1()
{
var answer1 = prompt("Enter your answer: "); //this variable only accessible inside the function answerPrompt1()
var convertedNum1 = parseInt(answer1, 10);
result = (convertedNum1 == 14)? "You're right!" :
"Sorry, that's incorrect.";
}
function showResult()
{
alert(result);
}
I'm currently following a tutorial and the person in the tutorial is coding css, html, and jquery all in one file. I split them up into seperate files. My problem is the code in the tutorial works when calling a function and mine does not, even though the code is exactly the same. Here is some of my code
//Jquery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
........
HTML File
<div id = "container">
</div>
<div id = "controls">
.....
Tutorial Code
<script type="text/javascript">
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
.......
It's exactly the same but for some reason my code does not work, I tested out both. And i know I'm linking to the correct jQuery files because my other function work fine no problem.
Full HTMl
JQuery Chatbot Tutorial
jQuery Chatbot v. 1.0 Tutorial
<div id = "container">
</div>
<div id = "controls">
<textarea id = "textbox" placeholder = "Enter your message here..."></textarea>
<button id = "send">Send</button>
<br>
<input checked type = "checkbox" id = "enter"/>
<label>Send on enter</label>
</div>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="chatbot.js"></script>
</body>
Full JQuery File
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13){
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
});
$("#send").click(function(){
var username = "<span class ='username' = >You: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if (prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
});
You might have error in the code before the call. Try:
$(function(){
alert('Debug me 2');
username();
alert('Debug me 2');
...
and see what happens.
Trying to do the following:
Store params from url, i.g. mydomain.com/page.html?cid=123456
If a user clicks on a button (they have a class of .btn-cta) it will take the params ?cid=123456 and add them to the new page those buttons link to /tour.html
I'm currently doing 1/2 of that with passing the params to an iframe on the page, now I need to get the above part working:
var loc = window.location.toString(),
params = loc.split('?')[1],
iframe = document.getElementById("signupIndex"),
btn = $('.btn-cta');
iframe.src = iframe.src + '?' + params;
Here's how I'd do it using jquery:
$('.btn-cta').each(function(i, el){
let $this = $(this); // only need to create the object once
$this.attr({
href: $this.attr("href") + window.location.search
});
});
And in Vanilla ES2015
document.querySelectorAll('.btn-cta')
.forEach(el => el.attributes.href.value += window.location.search);
This takes all the elements that have class .btn-cta and appends the page query string to each of their href attributes.
So if the page url is `http://domain/page.html?cid=1234
Tour
becomes
Tour
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function() {
var loc = window.location.href;
var params = loc.split('?')[1];
$(".btn-cta").click(function(){
window.open("tour.html?"+params,'_self',false);
});
});
</script>
</head>
<body>
<button type="submit" class="btn-cta">Click Me</button>
</body>
</html>