I'm trying to write some javascript that will grab the inner text of li elements (1-16) and put them into hidden fields.
var myValue9 = document.getElementById("fileName9").value;
oForm.elements["fileName9"].value = myValue9;
<input name="fileName9" type="hidden" id="fileName9" />
<li id="wavName9"> Some Text </li>
How do I return the text in between the <li> and put into the hidden field?
Simple JavaScript:
document.getElementById("fileName9").value = document.getElementById("wavName9").innerText;
You could, in this case, also use innerHTML but that would also give you the HTML the element contains.
LI tags don't have a .value property. Using plain javascript, you could do it this way:
oForm.elements["fileName9"].value = document.getElementById("wavName9").innerHTML;
Or, to do all of them from 1 to 16, you could use this loop:
for (var i = 1; i <= 16; i++) {
oForm.elements["fileName" + i].value = document.getElementById("wavName" + i).innerHTML;
}
Or since you also tagged your post for jQuery, using jQuery you could do it like this:
$("#fileName9").val($("#wavName9").text());
Or, to do all of them from 1 to 16:
for (var i = 1; i <= 16; i++) {
$("#fileName" + i).val($("#wavName" + i).text());
}
Use jQuery to do it.
var myvar = $("#wavName9").html()
I think this will do in for all li's
$("li[id^=wavName]").each(function(){
var $this = $(this);
$this.closest("input[id^=fileName]").val($this.text())
});
Create your li's with id's following such a structure: listitem-n, where n is 1-16 and input fields following the same structure hiddeninputs-n (n = 1-16)
using jfriend00's code, add it in a loop that will traverse 16 times, incrementing a count variable that you will use to transfer the data from list items to hidden inputs
var count = 0;
for( i=0; i < 16; i++){
count ++;
$("form #hiddeninput-"+count).val($("#listitem-"+count).text());
}
Better validate the code, but there's the general idea.
You could also create the hidden fields in javascript from scratch, which would make the code abit more stable IMO as there's less chances of a hidden field missing in the form when the js is executed.
Using jQuery:
$('#fileName9').val($('#wavName9').text());
Note that you can change .text() to .html() to return the HTML structure rather than just the text.
You could automate this for multiple <li>'s like so:
$('li[id^="wavName"]').each(function () {
var number = this.id.replace('waveName', '');
$('#fileName' + number).val($(this).text());
});
This selects all <li>'s who's id starts with "wavName" and stores the text within the <li> tag in the hidden input who's id starts with "fileName" and ends with the same integer as the <li> tag.
Related
Here i want to select the second LI of UL using DOM and mainuplate it , i know how to select first and last element but i am not able to select second ,third and so on element . How to do it?
I want to change the "second" written on the html page(see picture 2 below) to my name using DOM.
let list = document.querySelector("ul").querySelectorAll("li");
for(let i = 1; i < list.length - 2; i++){
list[i].doSomething();
}
You can use querySelectAll and length proprety like this:
var el = document.querySelectorAll('ul > li');
el[el.length-2].textContent="Shubham Kandpal";
or using jquery's eq() method like this:
$("ul > li").eq(-1).text("Shubham Kandpal");
Use nth-child
ul > li:nth-child(2)
Please use this javascript selector to select the Second (LI) option.
document.querySelector('ul li:nth-child(2)')
Another possible way, besides querySelector, is by adding a class or an Id and getting it:
Adding using a class
function myFunction() {
let x = document.getElementsByClassName("className");
x[1].textContent = "Whatever you want to name it now";
// 1 because it is the second position
}
or by id
function myFunction() {
let x = document.getElementById("idName");
x.innerHTML = "Whatever you want to name it now";
// You can also use innerHtml to change the text
}
There are href links on the page, its text is not complete. for example page is showing link text as "link1" however the correct text should be like "link1 - Module33". Both page and actual texts starts with same text (in this example both will starts with "link1").
I am getting actual text from JSON object from java session and comparing. If JSON text starts with page text (that means JSON text "link1 - Module33" startsWith "link1" (page text), then update "link1" to "link1 - Module33".
Page has below code to show the links
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_2_a"> link1 </a></li>
<li id="accounts_mb_11_id"><a href="javascript:void(0)" class="linksmall"
id="accounts_mb_11_a"> link2 </a></li>
.
.
.
// more links
</ul>
</div>
Note : li id is not static its different for each page text, however ul id is static.
I am reading correct & full link text from JSON object (from java session) as below
var sessionValue = <%= json %>; // taken from String array
and reading page text as below :-
$('.display_links li').each(function() { pageValue.push($(this).text()) });
sessionValue has correct updated text and pageValue has partial texts. I am comparing using below code
for(var s=0; s<pageValue.length; s++) {
var pageLen = $.trim(pageValue[s]).length;
for(var w=0; w<sessionValue.length; w++) {
var sesstionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, pageLen);
if($.trim(newV)==$.trim(pageValue[s])){
**// UPDATING VALUES AS BELOW**
pageValue[s]=sessionValue[w];
}
}
}
I am trying to update page value text to session value text as pageValue[s]=sessionValue[w]; (in above code) but its not actually updating the values. Sorry for the poor comparing text logic.
Please help, how to update it dynamically in the loop after comparing to make sure I am updating the correct link text.
pageValue[s]=sessionValue[w]; just updates the array; it has no effect whatsoever on the li's text.
If you want to update the li's text, you need to do that in your each. Here's an example doing that, and taking a slightly more efficient approach to the comparison:
$('.display_links li a').each(function() {
var $this = $(this);
var text = $.trim($this.text());
var textLen = text.length;
for (var w = 0; w < sessionValue.length; ++w) {
var sessionText = $.trim(sessionValue[w]);
if (sessionText.substring(0, textLen) == text) {
text = sessionText;
$this.text(text);
break; // Found it, so we stop
}
}
pageValue.push(text); // If you want it for something
});
I think it's cleaner to just select the elements you care about (in this case the anchor tags) and then use built-in functionality to compare rather than reimplementing a startsWith function.
var sessionValue = ['link1 - Module33', 'link2 - foobar'];
$('.display_links li a').each(function() {
var $this = $(this);
var text = $this.text().trim();
sessionValue.forEach(function(sessionValue) {
if (sessionValue.startsWith(text)) {
$this.text(sessionValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="display_links">
<ul id="accounts_links_container">
<li id="accounts_mb_2_id"> link1 </li>
<li id="accounts_mb_11_id"> link2 </li>
</ul>
</div>
The result of $(this).text() is a primitive string, not a reference to the textNode of the element. It doesn't matter if you update pageValue, because it is not related to the original element.
Instead of pushing the strings to an array to process, you can stay inside the $.each() loop and still have access to the elements, which is needed to update the text. Something like this:
$('.display_links li').each(function() {
var $li = $(this);
var liText = $.trim($li.text());
var liLen = liText.length;
for(var w = 0; w < sessionValue.length; w++) {
var sessionLen = $.trim(sessionValue[w]).length;
var newV = sessionValue[w].substring(0, liLen);
if ($.trim(newV) === liText) {
**// UPDATING VALUES AS BELOW**
$li.text(sessionValue[w]);
}
}
});
I am a noob and thought I would take a shot at this.
Here is my approach although the sessionValue array is a bit foggy to me. Is the length undetermined?
I declared var's outside of the loop for better performance so they are not declared over and over.
Iterate through elements passing each value through Compare function and returning the correct value and update immediately after all conditions are satisfied.
var i = 0;
$('.display_links li a').each(function(i) {
$(this).text(Compare($(this).text(), sessionValue[i]));
i++;
});
var Compare;
var update;
Compare = function(val1, val2) {
// Check if val1 does not equal val2 and see if val2 exists(both must be true) then update.
if(!val1 === val2 || val2) {
update = val2
}
return update;
}
<div id='images'><img id='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
How to remove all <div> with the loop with Javascript?
Here is my code:
var value = document.getElementsByTagName("images");
for (var i = 0; i < value.length; i++) {
$(value[i]).remove();
}
You can only use same id value once per page. Change it to class, i.e. images
You will then have multiple div with class images and will be able to easily remove the spinners like this:
$(".images").remove();
If you have a lot of spinners, just wrap them with a div and remove the div. Something like this:
HTML:
<div id="jedi-wrapper">
<div class="images">
...
</div>
</div>
jQuery:
$("#jedi-wrapper").remove();
From the image, it looks like you are loading some values using AJAX. Why don't you remove the image on success?
Hope that helps
Seem like you want to remove all div with id images, but id is unique, you can use class instead:
<div class='images'><img class='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
then you can do:
$('.images').remove()
With your code you can do this:
document.getElementsByClassName("images").remove();
or more like jQuery:
$('.images').remove();
Althoug you can try this too:
var value = document.getElementsByClassName("images");
for (var i = 0; i < value.length; i++) {
$(value).eq(i).remove();
} //-------^^^^^^--------------you can make use of `.eq()` here
What your issue is there is no tag name like 'images' as your var suggests.
var value = document.getElementsByTagName("images");
images is the class name so you can use this:
document.getElementsByClassName("images")
Get element by ID, there's nothing with document.getElementsByTagName("images")
var c = document.getElementById('images');
var i, item = c.childNodes;
for (i = item.length; i--;) {
c.removeChild(item[i]);
}
You should probably be using class="images" instead of id="images" if that element is being rendered multiple times.
But to do this in a loop with raw javascript, you will need to first get the elements, convert them to an array, and then remove them in a loop.
var imageElements = doc.getElementsByClassName('images'),
images = Array.prototype.slice.call(imageElements);
for (var i = 0, l = images.length; i < l; i++) {
images[i].remove();
}
Notice that I don't just loop through imageElements... That's because getElementsBy...() returns a live list, so as soon as you remove() one of them, the list will be mutated and you will start running into undefined elements and javascript errors. To solve this, simply convert the live list to an array with Array.prototype.slice.call() and then loop through that array, removing the elements from the page.
How to use JavaScript or CSS to change a string on a page.
I will have around 50 elements which contain tags separated by commas ie
<a name="tagslist">Skrillex, dubstep, dance</a>
I want to using JavaScript take each of these words and style them differently so that they don't look like they are separated by commas but on different lines. The problem is there can be a variable amount of tag lists on the page.
Is there any way i can achieve this easily?
First of all, get out of last milennium and use this HTML:
<div id="tagslist">Skrillex, dubstep, dance</div>
Then you can do this:
var elm = document.getElementById('tagslist');
elm.innerHTML = elm.innerHTML.replace(/, /g,'<br />');
You can of course do something more complex, like this:
elm.innerHTML = "<div class='tag'>"+elm.innerHTML.replace(/, /g,"</div><div class='tag'>")+"</div>";
Alternatively, you can use real DOM methods:
var elm = document.getElementById('tagslist'), tags = elm.firstChild.nodeValue.split(", "),
l = tags.length, i, div;
elm.removeChild(elm.firstChild);
for( i=0; i<l; i++) {
div = elm.appendChild(document.createElement('div'));
div.appendChild(document.createTextNode(tags[i]));
// apply styles, className, etc. to div
}
$('a[name="tagslist"]').html(function(_, html){
var arr = [],
tags = html.split(/\s*,\s*/);
for (var i=0; i<tags.length; i++)
arr.push('<div class="whatever">' + tags[i] + '</div>');
return arr.join('');
});
Consider using an existing library such as http://ivaynberg.github.com/select2/#tags
You would have to have separate anchor tags for each one for them to be styled differently. For line breaks between them, you could put br tags between them.
What you want to do is not possible. A more ideal solution would be to have the html be rendered like so:
<span class="tagslist">
Skrillex
dubstep
dance
</span>
This way, you have complete control over the styling using CSS.
I have a form in which there are textbox(s) added dynamically using jquery.
The textbox ids is formed as an array, i.e. Quantity[0], Quantity[1], Quantity[2] ...
I want to add the numbers in these textbox(s) and display the value in another textbox named "total_quantity" preferably when the focus is shifted out of the array textbox.
How can I do it? I dont mind using jQuery or plain javascript, which ever is easier.
I would suggest giving a common class to your quantity fields such that:
<input type="text" class="quantity" onblur="calculateTotal();" />
Then you would be able to define the following function with jQuery:
function calculateTotal() {
var total = 0;
$(".quantity").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
$("#total_quantity").val(total);
}
The onblur event will fire each time the focus is shifted from the quantity fields. In turn, this will call the calculateTotal() function.
If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. This will match all the text boxes that have an id starting with: Quantity[
var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);
Use the following function, if one can't use document.getElementsByName(), as some MVC frameworks such as Struts and Spring MVC use the name attribute of a text to bind the element to a backend object.
function getInputTypesWithId(idValue) {
var inputs = document.getElementsByTagName("input");
var resultArray = new Array();
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute("id") == idValue) {
resultArray.push(inputs[i]);
}
}
return resultArray;
}