javascript alert value from a tag - javascript

I have on a page a tag links generated from a database with an id. What im trying to do is in an alert box display the text inside the a tag.
Ive tried to have a look to see if I can see a previous question, which I have come up with the following but all I get in the alert box is object HTMLCollection
I have the following code:
<a id="bet" onclick="addSlip();" class="btn btn-round" style="text-align: left;">'.$home->one.' <span>'.$home->two.'</span></a>
and...
function addSlip() {
document.getElementById('bet').innerHTML=bet;
alert(bet);
}
Thanks for any constructive answers

You should do the following
function addSlip() {
var bet = document.getElementById('bet').textContent;
alert(bet);
}
the rest as it is.
or using jquery
function addSlip() {
var bet = $("#bet").text()
alert(bet);
}
The main problem of your program was that the alerted variable had no value. (undefined)
The way you wrote it if the variable bet had a value would change the innerHTML of the of the a tag to that value.
Now to the using innerHTML or textContent part. As mentioned here in terms of performance the textContent is better

You need to reverse the variable assignment of bet:
function addSlip() {
var bet = $("#bet").text();// or $("#bet").html() if you want the HTML alerted
alert(bet);
}

In your case alert will give you the HTML Object Collection only.
When you have an element with id, then you can access them anywhere in javascript
e.g. for the following HTML
<div id="bet">This is a div </div>
in JS
alert(bet);
will give you the html object collection.
Solution for you is update your code
function addSlip() {
document.getElementById('bet').innerHTML=bet;
alert(bet);
}
to
function addSlip() {
alert( document.getElementById('bet').innerHTML);
}
If there is some html elements also in the div you can update the function with
function addSlip() {
alert(document.getElementById('bet').textContent);
}

Related

can't get value from onclick function javascript

I have a function where I am trying to get a value from an onclick event.
Here is the element attribute that gives the function to the element:
listcontainer.setAttribute('onmousedown',"knowbe4campaignspecific(this)")
Here is the function code:
function knowbe4campaignspecific(ele){
console.log(ele.value)}
However it will say undefined in the developer console.
If I just print the element by itself it will show the value inside so I must be missing something basic.
function knowbe4campaignspecific(ele){
console.log(ele)}
##RESULTS##
<ul value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>
Let me know if anything else is needed and I will update this post. Thanks!
As mentioned, value isn't a valid attribute of <ul>. You can still use it and access it through element.getAttribute but using datasets is more extendable and the correct implementation - you can access those through element.dataset
document.querySelector('.ms-List').setAttribute('onmousedown',"knowbe4campaignspecific(this)")
function knowbe4campaignspecific(ele){
console.log(ele.getAttribute('value'))
console.log(ele.dataset.value)
}
<ul value="183085" data-value="This is the better way" class="ms-List"><li> something</li></ul>
On elements that are not inputs you want to use the data attribute.
I believe this should work
<ul data-value="183085" onmousedown="knowbe4campaignspecific(this)" class="ms-List"></ul>
And then
function knowbe4campaignspecific(ele){
console.log(ele.dataset.value)}

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

passing values to a function does not work when inside for loop

I'm mapping currencies from a json file and i render the mapped currencies to a component. I have a .php file like this
<div class="currency-switch-container" id="currency_container">
<span style="font-size:12px;font-weight:bold">All currencies</span>
<div id="currency-map" style="margin-top:15px"></div>
</div>
I refer the div in the above component in my js file as follows
let currencyMap = jQuery("#currency-map");
And when my jQuery document is ready i'm doing the following
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"
class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</span>`)
}
});
}
and my function is like this
function onCurrencyClick(val){
console.log("val",val);
setCookie("booking_currency", val, 14);
}
Here the function does not work. But if i do not pass anything to the function it seems to work as i can see the log in the terminal.
Hi your expression ${data[c].abbreviation} will put the value into function string without string quotes i.e. the resultant would be onCurrencyClick(abbreviation) while it should be onCurrencyClick('abbreviation').
please use onclick="onCurrencyClick('${data[c].abbreviation}')" instead.
Instead of using the inline onclick, use event delegation. This means that you have a single event listener that handles all the events from the children and grandchildren. The modification is a very minor one seeing the example here below.
A reason for doing this is that you keep your JavaScript inside your JS file. Like now, you encounter a JS error and have to look for it in your HTML. That can get very confusing. Also however inline onclick listeners are valid, they are outdated and should be avoided unless there is absolutely no other way. Compare it with using !important in CSS, same goes for that.
function onCurrencyClick(event){
var val = $(this).val();
setCookie("booking_currency", val, 14);
}
currencyMap.on('click', '.currency-item', onCurrencyClick);
This example takes the val that you try to insert from the value attribute from the clicked .current-item. <span> elements don't have such an attribute, but a <button> does and is a much more suitable element for it expects to be interacted with. It is generally a good practice to use clickable elements for purposes such as clicking.
In the example below you see the button being used and the abbreviation value being output in the value attribute of the <button> element and can be read from the onCurrencyClick function.
jQuery(document).ready(function($) {
$.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {
for(let c in data){
currencyMap.append(`
<button value="${data[c].abbreviation}" class="currency-item">
<span>
${data[c].symbol}
</span>
<span>
${data[c].currency}
</span>
</button>
`)
}
});
onclick will not work for a dynamically added div tag
Yo should follow jQuery on event
Refer: jQuery on
Stackoverflow Refer: Dynamic HTML Elements

javascript set variable from .text method

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

Create a region on HTML with changing values

I am a beginner in HTML and I want to create a region on a HTML page where the values keep on changing. (For example, if the region showed "56" (integer) before, after pressing of some specific button on the page by the user, the value may change, say "60" (integer) ).
Please note that this integer is to be supplied by external JavaScript.
Efforts I have put:
I have discovered one way of doing this by using the <canvas> tag, defining a region, and then writing on the region. I learnt how to write text on canvas from http://diveintohtml5.info/canvas.html#text
To write again, clear the canvas, by using canvas.width=canvas.width and then write the text again.
My question is, Is there any other (easier) method of doing this apart from the one being mentioned here?
Thank You.
You can normally do it with a div. Here I use the button click function. You can do it with your action. I have use jquery for doing this.
$('.click').click(function() {
var tempText = your_random_value;
// replace the contents of the div with the above text
$('#content-container').html(tempText);
});
You can edit the DOM (Document Object Model) directly with JavaScript (without jQuery).
JavaScript:
var number = 1;
function IncrementNumber() {
document.getElementById('num').innerText = number;
number++;
}
HTML:
<span id="num">0</span>
<input type='button' onclick='IncrementNumber()' value='+'/>
Here is a jsfiddle with an example http://jsfiddle.net/G638z/

Categories

Resources