how to display text in div dynamically - javascript

I have searched on the forum and saw posts about changing text dynamically upon click. But in my case I want to change the display dynamically when loading the page from beginning. I already have a function that figure out what I should display:
function phone()
{
//code here
return phone;
}
And my question is how to display the returned phone number in the div below to replace the 1.888.888.8888 part. Can anyone offer some insights? Thank you!
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call 1.888.888.8888</span></span>
</div>

I would change the HTML to add another <span> tag around the phone number and give that span tag an id attribute in order to access it easily (broke it up on separate lines to reduce scrolling):
<div class="add-info">
<span class="rightfloat">
Order online <span class="red">
or call <span id="contact-number"></span>
</span>
</span>
</div>
Then after the page loads update the span with whatever value you want:
window.onload = function() {
document.getElementById('contact-number').innerHTML = PHONE_NUMBER_VALUE;
}
In JQuery, it would be:
$(document).ready(function () {
$('#contact-number').html(PHONE_NUMBER_VALUE);
});

You can,
<body onload="phone();">
<div class="add-info">
<span class="rightfloat">Order online <span class="red">or call
<span id="phone"></span>
</span>
</div>
</body>
And set the value when the function runs;
function phone() {
document.getElementById("phone").innerHTML = "1.888.888.8888";
}

Instead of returning 'phone', why don't you put an id on your span and just use
document.getElementById('spanId').innerHTML = phone
in your javascript?

Call you code from the window.onload event.

I would separate the number into additional <span> tag with its own id and change content of it with js...
document.getElementById('id_of_span').innerText = 'new number';

Try this
<script>
function phone(number) {
var redText = document.getElementByClassname("red")[0];
redText.innerHTML = "or call " + number;
}
</script>
To call it you can use clicks, loads or anything else. For example
<script>
window.onload = phone('NEW NUMBER HERE');
</script>
Bear in mind that adding another window onload function later will displace this one, so you would either need to add to it, or use a double delegate function, but that's another story...

Related

Javascript get HTML of selected text nodes

I got the following HTML:
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:
var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.
If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.
Thank you.
EDIT:
There has been a similar thread before, here is a working solution:
https://jsfiddle.net/hallleron/wg1pbwbf/2/
Basically you loop through the siblings in the selection to get each value and then parse the array as string to display it in my result paragraph for better visuals.
ORIGINAL:
If you want a jQuery-free version, here is a fiddle: https://jsfiddle.net/hallleron/wg1pbwbf/
The whole Javascript Part is the following:
document.getElementById('editable_phrase').addEventListener("click", getDataId);
function getDataId(){
console.log(window.getSelection().anchorNode.parentElement.attributes[0].nodeValue);
}
So every time the event listener detects a click, it gets the selected text/span and extracts its data-id attribute from the object.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
<span data-id="42">My</span>
<span data-id="43">very</span>
<span data-id="1">first</span>
<span data-id="21">phrase</span>
</div>
<script>
$('#editable_phrase').on('click','span',function(){
var res = $(this).attr('data-id');
alert(res);
})
</script>

HTML Parsing using javaScript

I am trying to get parse HTML document.
this is the HTML:
<h1>
<span class="memName fn" itemprop="name">Ankur Arora</span>
<span class="display-none" itemprop="image">http://photos1.meetupstatic.com/photos/member/3/8/f/8/member_249974584.jpeg</span>
<span class="display-none" itemprop="url">http://www.meetup.com/Meetup-API-Testing/members/191523682/</span>
</h1>
I need to get the picture and the name.
I try this code:
var name = document.querySelector("memName fn").name;
Anyone can help me? I'm new in javaScript...
Thanks
To get the inner text, you can use the text() function, like this:
HTML:
<span class="memName fn">Ankur Arora</span>
Jquery:
var memName = $(".memName").text();
console.log(memName); // Via console log
alert(memName); // Alert it
It's easy with jQuery. Just include it in your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Then use .text() or .html() to extract the content of the span-elements
var pictureLink = $("span[itemprop='image']").text();
//.html() also gets the html-elements inside
var name = $("span[itemprop='name']").html();
https://jsfiddle.net/bh9mebru/
You can also use innerHTML to get the text.
<span id="memId" class="memName fn">Ankur Arora</span>
document.getElementsByClassName('memName') - This will give the list of elements having the class 'memName'
To get the first element's inner text use document.getElementsByClassName('memName')[0].innerHTML
or access by id .
document.getElementById('memId').innerHTML

How to pull an ID from a link the User inputted

HTML:
<body>
<input type="text" id="userINPUT" />
<button onclick="updatev1()">Submit</button>
<div id="video1">
</div>
<div id="video2">
</div>
</body>
The html has two divs, and an input text box,and of course, a submit button. What the user is supposed to do is enter a youtube link into the text box, and submit it.
JavaScript:
var userIN1 = document.getElementById("userINPUT");
var userIN2 = userIN1.value;
var index = userIN2.substring(string.indexOf('=') -1);
alert(index);
Now what I want the JavaScript to do is to grab the youtube link, and pull the ID from said link.
EX. The user inputs the link. 'http://www.youtube.com/watch?v=-K7lEFmFcKs', then the JavaScript would take the link and grab '-K7lEFmFcK' and store it in a variable for later use.
'userIN2' would be the variable that would store the user input value, and 'index' would take the whole ID coming after the '=' symbol of the link and store it.
I know this is considered a small task, but any help would be great.
Thanks!
Oh, and I heard these things can be done A LOT easier with jQuery. Should I use jQuery instead?
Sure should. It'd be that simple:
$('button').click(function() {
var userIN2 = $('#userINPUT').val();
var index = userIN2.split('=');
index = index[1];
});
This collects everything after v=
http://jsfiddle.net/7aZqB/4/
function getID(str) {
return str.substring(str.indexOf('=') -1).replace('v=', '');
}

Each div must increments its counter upon clicking

I've three divs. Each div must increment its counter val upon clicking them.
HTML:
<body>
<content>
<div id="box1" class="v1" onclick="counter('box1')";>A : <span class="num">0</span></div>
<div id="box2" class="v2" onclick="counter('box2')">B: <span class="num">0</span></div>
<div id="box3" class="v3" onclick="counter('box3')">C: <span class="num">0</span></div>
</content>
</body>​
Javascript:
function counter(id){
var id = document.getElementById(id);
$('#id').click(function () {
update($("span"));
});
}
function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
​
Here is the code demo
You are doing a lot of work that jQuery would do for you. If you change your class to simply box and use the ID's to style your content, you can do the whole thing like this:
<body>
<content>
<div id="box1" class="box">A: <span class="num">0</span></div>
<div id="box2" class="box">B: <span class="num">0</span></div>
<div id="box3" class="box">C: <span class="num">0</span></div>
</content>
</body>
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) + 1 );
});
});
Example: http://jsfiddle.net/ddvQU/1/
Some thoughts:
If a style is unique to a single element (now and in the future), you should be using IDs. Styles that are (or will be) common to multiple elements should use classes.
Using inline javascript onclick='blah()' is more difficult to manage, as it is not as easy to debug, does not allow for code reuse, and forces you to make updates in lots of places when you change code. It also makes you do nasty things like escaping quotes.
var id = document.getElementById(id); <= The whole reason we have jQuery is so that we don't have to do this. Simply do $('#'+id). (ok, maybe not the whole reason, but one of them).
You don't need to do the above if you attach a jQuery handler to your class of elements (see the first bullet). The handler will already have a reference to the object, even if it doesn't even have an ID.
I would use .on() instead of .click(), but as you look to be new to jQuery, get this to work first, and then look into why on() is better, and how to do it.
Assign a click function to your div that does:
$('#div_id').html(parseInt($('#div_id').html())++)
or something along those lines.
http://jsfiddle.net/4eqve/32/
Use a closure to store a counter variable for each DIV.
Attach a click handler.
Change counter function to this:
function counter(id){
update( $('#'+id+">span") );
}
http://jsfiddle.net/4eqve/24/
demo stores each count in data. One big thing that would have helped you is apply a common class to the elements you want to bind handler too as you'll see in this demo with added class "box"
If you're using jQuery then you might as well use the click handler it provides. You were quite close with your implementation, but you need to make sure that you're referencing the correct elements. I changed it so that you are passing the box div to the update function, that then selects the correct span from inside that div element.
// jQuery onclick for the boxes
$('#box1, #box2, #box3').click(function() {
update(this);
});
function update(j) {
var span = $(j).children('span');
var n = parseInt(span.text())+1;
span.text(n);
}
Here's the jsFiddle: http://jsfiddle.net/4eqve/29/
​
Fixed that for you.
It is much cleaner when you have clean html, and seperate the javascript to do the work.
<body>
<content>
<div id="box1" class="count-div">A : <span class="num">0</span></div>
<div id="box2" class="count-div">B: <span class="num">0</span></div>
<div id="box3" class="count-div">C: <span class="num">0</span></div>
</content>
</body>​
$(function(){
$(".count-div").click(function(){
amount = 1;
value = parseInt($(this).find("span").html());
$(this).find("span").html(value+amount);
});
});
You can even clean that up more so you have less code. If you have any question ask me
http://jsfiddle.net/4eqve/33/
There are many bugs in your script. Not to mentione, the markup selection is quite vague.
With a little update to some mark-ups, we can do this with a tiny snippet.
$(".clicable").click(function() {
$(this).children("span").html(parseInt($(this).children("span").html()) + 1);
});
Check the demo here

Data only to click the div

Good morning, everyone.
I have a doubt. I have a list of div. textarea with text inside it and inside. text for a button event. Want to get only the data from the textarea div that the person clicking the button.
I would be very grateful for the help. thanks
Example code.
<div class="text">
<textarea id="texts" class="texts" rows="5" cols="45" name="textarea"> </ textarea>
<div class="bt" id="1234556">
<div class="button"> Send </div>
</div>
</div>
$('.button').click(function() {
var text = $('#texts').val();
// do something with text
alert(text);
});
Working demo at http://jsfiddle.net/PPcxm/
As long as you have the same structure (and presuming you have more than one example on the page as the button is a class and textarea is an id, the following would work:
$(".button").click(function()
{
var text = $(this).parent().prev().val();
});
Since you have a list of div.text your best bet is to query based upon the structure of your DOM.
$(".button").click(function() {
var $textArea = $(this).parents(".text").find(".texts");
//Do something with $textArea.Val();
});
What we simply do is call .parents() on the current div.button which will allow us to get the div.text element. From there you can simply find your textarea.texts element and get the corresponding value.
Code example on jsfiddle.

Categories