Get only text value where the user clicked it
HTML code
<body>
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
<pre>
</div>
</body>
In the above code I am using pre tag, I have a long list of user so I want every user on next line
When the user click on zelketg, only I want zelketg under javascript alert box instead of whole text.
I tried the below JavaScript but it didn't works, It give me the whole text under div
$(document).click(function(event) {
var text = $(event.target).text();
alert(text);
});
Contents of pre tag are not identifiable as an individual nodes, so you need to do some pre-conditioning so that they can be identified as an individual nodes.
var preNode = document.querySelector( "pre" );
function preCondition()
{
var text = preNode.innerText;
preNode.innerHTML = text.split("\n").map( s => "<div>" + s + "</div>" ).join( "" );
}
preCondition();
Now you can add a click event handler on the pre-tag
preNode.addEventListener( "click", function(){
console.log(event.target.innerHTML);
});
Demo
var preNode = document.querySelector( "pre" );
function preCondition()
{
var text = preNode.innerText;
preNode.innerHTML = text.split("\n").map( s => "<div>" + s + "</div>" ).join( "" );
}
preCondition();
preNode.addEventListener( "click", function(){
console.log(event.target.innerHTML);
});
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
</pre>
</div>
Try as follows might help
$(document).click(function(event) {
var text = $(event.target).text();
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="test">
<pre>
<i>zelketg 1</i>
<i>gcaotydv 14</i>
<i>cdbot_i 11</i>
<i>pacdhss12 1</i>
<i>boters 1</i>
<pre>
</div>
</body>
Go over each line beforehand and turn them into span elements so you can handle them separately.
var lines = $("#test pre").text().split("\n");
$("#test pre").empty();
$.each(lines, function(n, elem) {
$("#test pre").html( $("#test pre").html()+'<span>'+elem+'</span><br>');
});
$('#test pre').click(function(event) {
var text = $(event.target).text();
console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="test">
<pre>
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
<pre>
</div>
</body>
Post-Fork of #Nisal Edu
You can replace your whole pre element as the following example for this you don't need any other library alike.
<body>
<div id="test">
<pre id="test_pre">
zelketg 1
gcaotydv 14
cdbot_i 11
pacdhss12 1
boters 1
</pre>
</div>
</body>
<script>
function getText(elem)
{
var user_name = elem.childNodes[0].innerHTML;
var user_id = elem.childNodes[1].innerHTML;
alert(user_name+","+user_id);
}
(function(){
var pre_tag = document.getElementById("test_pre");
var pre_text = pre_tag.innerHTML;
var pre_elem = pre_text.split('\n');
var doc_string ="" ;
for(item in pre_elem)
{
var arr = pre_elem[item].trim().replace(" ",",").split(",");
doc_string += "<p onclick='javascript:return getText(this);'><span>"+arr[0] +"</span><span> "+ arr[1] +"</span></p>";
}
document.getElementById("test_pre").innerHTML = doc_string;
})();
</script>
Related
Basically what I need to do is wrap this code output
<a id="show_selected">Click to Show</a>
<div id="selected"></div>
<script type="text/javascript">
function showSelect(){
$("#show_selected").bind("click", function (e) {
e.preventDefault();
$('#selected').text($("#fvip").mapster("get"));
});
}
showSelect();
</script>
which is right now is just plain
<div id="selected">001,002,003,004</div>
to become
<div="selected">
<div class="something">001</div>
<div class="something">002</div>
<div class="something">003</div>
<div class="something">004</div>
</div>
how can I do that? Is that possible? Many thanks
EDIT with brk 's help below:
I try incorporate it in my code like this:
function showSelect(){
$("#show_selected").bind("click", function (e) {
e.preventDefault();
$('#selected').text($("#fvip").mapster("get"));
let wrapContainer = ""
let stringArray = $("#selected").text().trim().split(' ');
$("#selected").empty()
stringArray.forEach(function(item, index) {
let wrapContainer = $('<div class="test">' + item + '</div>');
$("#selected").append(wrapContainer)
});
});
}
showSelect();
but what I'm getting is:
<div id="selected">
<div class="test">001,002,003,004</div>
</div>
where am I doing wrong?
You can get the text and split it. Then loop over that and put that inside a div . Then append the div to the parent element
let wrapContainer = ""
let stringArray = $("#original").text().trim().split(' ');
$("#original").empty()
stringArray.forEach(function(item, index) {
let wrapContainer = $('<div class="test">' + item + '</div>');
$("#original").append(wrapContainer)
});
.test {
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="original">001 002 003 004</div>
Hello I need a quick hand, I have this div below
<div class="price">$1500</div>
I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.
<span class="payment">Pay as low as $"result here" </span>
I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.
First get text of div var text = $('.price').text(); // "$1500"
Then parse it as integer var price = text.replace(/[^\d]/, ''); // "$1500" -> 1500
Finally place text to where it belongs: $('.payment').text('Pay as low as $'+(price / 2 / 6));
$(document).ready(function () {
var text = $('.price').text();
var price = text.replace(/[^\d]/, '');
$('.payment span').text(price / 12);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $<span></span> </span>
Here, this one is pure javascript, try not to overcomplicate things
<html>
<body>
<div id="num">1500$</div>
<div id="num2"></div>
<script>
var number = document.getElementById("num").innerHTML.replace("$", "");
number = number / (2 * 6);
document.getElementById("num2").innerHTML = "Pay as low as " + number + " here";
</script>
</body>
</html>
You can achieve this as below mentioned.
$(document).ready(function(){
var price = $(".price").text(),
price = price.replace('$', '');
finalPrice = (price/2).toFixed(2);
$(".final-price").text(finalPrice/6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<br> <br>
<div class="payment">Pay as low as $<span class="final-price"></span> </div>
get the text() of the element.
replace the $ sign
And divide by (2*6)
Apply with some Math.abs function its will calculate the result
Then apply the span and append into your body
var a = Math.abs(parseInt($('.price').text().replace('$',''))/(2*6))
$('body').append('<span class="payment">Pay as low as $'+a+' </span>')
.payment{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
Try this
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
Demo
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $"result here" </span>
What you should do:
Get the .price div's text.
convert it to an int.
Now you should divide it with (value/2)/6
Put the value in the desired target element.
var price = +$('.price').text().slice(1);
var pay = (price/2)/6
$('p').text("Pay as low as $"+pay);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<p></p>
hope it help.
/*define a function to Deleting all characters other than numbers. in element*/
function checkIsInteger(sTr){
var newstr = "";
if(typeof sTr !== "undefine" && sTr!=""){
var indexInt = ['0','1','2','3','4','5','6','7','8','9'];
for(var i=0;i<sTr.length;i++){
var cek = sTr.substr(i,1)
if(indexInt.indexOf(cek)>=0){
newstr += sTr.substr(i,1);
}
}
}
return newstr;
}
$("#res").html((parseInt(checkIsInteger($("#price").html()))/2)/6);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="price" id="price">$1500</div>
<label class="payment" id="pym">Pay as low as $<span id="res">result</span> here </label>
I have multiple h2 tags and every tag contains text and has a custom attribute called data-options. This attribute has multiple options separated by commas and one of these options is the h2 tag text itself.
HTML:
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
jQuery:
var indexArray = ['happy','1'];
$('h3').each(function(i){
var $this = $(this),
value = $this.text(),
code = $('body').html();
code = code.replace(value, indexArray[i]);
$('body').html(code);
});
This is what I expect:
<h3 id='test' data-options='happy,sad,fantastic'>happy</h3>
<h3 id='test2' data-options='1,2,3,4'>1</h3>
Instead I get this:
<h1 id="test" data-options="happy,happy,fantastic">sad</h1>
<h3 id="test2" data-options="1,2,3,4">3</h3>
As you can see the script changes the first text it encounters, not the one inside the tags.
This is a working demo for the script : http://jsfiddle.net/fs1sfztx/
It makes no sense to do a replace unless you're searching. Which means you have to be provided what to search for and what to replace it with. So far only the text to in the h3 is given.
Assuming that each index in indexArray matches the index of each h3 element, then you can compare the current indexArray element indexArray[i] with each of the words in the corresponding elements data-options attribute. When a matches, set the innerText prop to that word.
var indexArray = ['happy','1'];
$('h3').text( function( i, txt ) {
var that = $(this);
var ntxt = txt;
$.each( that.data('options').split(','), function( j, u ) {
indexArray[i] !== u || (ntxt = u);
});
return ntxt;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
If all you wanted is to play with the replace method, then you could use something like this:
var indexArray = ['happy','1'];
var allhtml = $('body').html();
$('h3').each( function( i ) {
var txt = $(this).text();
var re = new RegExp( '>' + txt + '<', 'g' );
allhtml = allhtml.replace( re, '>' + indexArray[i] + '<' );
});
$('body').html( allhtml );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 id='test' data-options='happy,sad,fantastic'>sad</h3>
<h3 id='test2' data-options='1,2,3,4'>3</h3>
I am unable to change the text inside my 'p' tag using this script
<script>
var firstItem = document.getElementByTagName('p');
firstItem.innerHTML = 'Adding Javascript';
</script>
You have several coding errors. Here's some corrected code:
<script>
var firstItem = document.getElementsByTagName('p')[0];
firstItem.innerHTML = 'Adding Javascript';
</script>
The correct method is document.getElementsByTagName('p'). Note the "s" at the end of "Elements".
Then, because document.getElementsByTagName('p') returns an HTML collection object, you have to either iterate over the collection or reach into the collection to grab a specific DOM object (which I did in my example with [0]).
And here's a working code snippet:
// change just the first <p> tag
document.getElementById("test1").addEventListener("click", function(e) {
var firstItem = document.getElementsByTagName('p')[0];
firstItem.innerHTML = 'Adding Javascript';
});
// change all the <p> tags
document.getElementById("test2").addEventListener("click", function(e) {
var items = document.getElementsByTagName('p');
for (var i = 0; i < items.length; i++) {
items[i].innerHTML = 'Setting All Items';
}
});
<button id="test1">Change text of first item</button><br><br>
<button id="test2">Change text of all items</button><br><br>
<p>This is some text</p>
<p>This is more text</p>
<p>This is and more text</p>
I am not sure why item count parentheses aren't being removed in this tiny fiddle example.
EDIT: Here is my result from looking at the working answer.
$.fn.itemcount = function(){
var text = $(this).text();
text = text.replace("(","").replace(")","");
$(this).text(text);
};
$("#prc").itemcount();
$.fn.sidecartcost = function(){
var el = $(this);
var text = $(this).text();
text = text.replace("Your sub total is", "").replace(". ", "");
$(this).text(text);
};
$('.SideCartCost').sidecartcost();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="prc">(7 Items)</div>
<div class="blank">Woo</div>
<div class="SideCartCost">Your sub total is $300.03. </div>
you are not replacing the html/text of the div like so http://jsfiddle.net/x5jeL/1/