javascript capture every value in a div - javascript

I have a div in which I render through javascript inputs and text dynamically. I am trying to capture the text of this div (both input values and text).
My first step if to capture the parent div:
let answerWrapper = document.getElementById("typing-answer-wrapper");
The issue now is that using the innerHTML will give me the whole html string with the given tags and using the inerText will give me the text, excluding the tags.
In the following case scenario:
the console inspect is:
What is the way to capture: $2.4 if the inputs have 2 and 4
and $null.null if the inputs are blank.
Any help is welcome

You could iterate over all of the element's child nodes and concatenate their wholeText or value else 'null'. For inputs the wholeText will be undefined. If they have no value we'll return 'null'. Be aware that spaces and line-breaks will also be included so you may want to strip these later (or skip them in the loop) but as a proof of concept see the following example:
var typingAnswerWrapper = document.getElementById("typing-answer-wrapper");
function getVal(){
var nodeList = typingAnswerWrapper.childNodes;
var str = "";
for (var i = 0; i < nodeList.length; i++) {
var item = nodeList[i];
str+=(item.wholeText || item.value || "null");
}
console.log(str);
}
getVal();
//added a delegated change event for demo purposes:
typingAnswerWrapper.addEventListener('change', function(e){
if(e.target.matches("input")){
getVal();
}
});
<div id="typing-answer-wrapper">$<input type="number" value=""/>.<input type="number" value="" />
</div>

Here's how you could do it :
function getValue() {
var parent = document.getElementsByClassName('typing-answer-wrapper')[0],
text = [];
const children = [...parent.getElementsByTagName('input')];
children.forEach((child) => {
if (child.value == '')
text.push("null")
else
text.push(child.value)
});
if (text[0] != "null" && text[1] == "null") text[1] = "00";
document.getElementById('value').innerHTML = "$" + text[0] + "." + text[1]
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<div class="typing-answer-wrapper">
$
<input type="number"> .
<input type="number">
</div>
<button onclick="getValue()">get value</button>
<div id="value"></div>

You can fetch input feild values by their respective ids $('#input_feild_1').val() will give the first feild value and similarly $('#input_feild_2').val() for second feild and contruct use them to construct whatever as u wish. As in your case this should work
value_1 = $('#input_feild_1_id').val()
value_2 = $('#input_feild_2_id').val()
you need something like "$ + value_1 + . + value_2"

Related

Dynamic Filter of Iframe with Two Input Fields

I'm attempting to make a dynamic filter on one iframe with two input boxes. Let's call the input boxes "Box 1" and "Box 2". When both boxes are not populated, I would like the iframe to display all of the information. When Box A is populated, I want it to display information on Box A. When Box B is populated as well, I would like both the filters to apply. When only Box B is populated, I would like the iframe to only display Box B's input.
One limitation I have is the changing nature of having one of the input boxes blank. I am limited to assigning a number to the input on the URL (e.g. - col1, op1, val1). If the "salModBox" is blank for instance, it needs to be dynamic enough to assign "serNumPrefBox" with col1, op1, val1). If both are populated, it would need to be col1, op1, val1 for "salModBox" and col2, op2, val2 for "serNumPrefBox". If neither are populated, well, it doesn't need to have col1 or 2 for that matter.
Expected output of the URL would ultimately look like this if both are populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod+"&col2=Variable%20Number%20Two&op2=EQ&val2="+serNoPre+"#/moreinfo/anotherID
Expected output of the URL with one variable populated:
https://example.com/#/embed/viz/longID/?col1=Variable%20Number%20One&op1=EQ&val1="+salesMod (or serNoPre) +"#/moreinfo/anotherID
With both of them blank, it would simply be the original URL source link. This would be a wide open search. A user isn't technically limited to values they can put in either input box.
function salModSnpFilter() {
var salModInput = document.getElementById('salModBox').value;
var serNumPrefInput = document.getElementById('serNumPrefBox').value;
var smSnp = '';
if (salModInput = ' ' and serNumPrefInput = ' ') {"https://en.wikipedia.org/wiki/IFrame"
} else if (salModInput = ' ' and serNumPrefInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput
} else if (serNumPrefInput = ' ' and salModInput != ' ') {"https://en.wikipedia.org/wiki/IFrame" + salModInput
} else if (salModInput != ' ' and serNumPrefInput != ' ' {"chttps://en.wikipedia.org/wiki/IFrame"+salModInput+serNumPrefInput
} else {"https://en.wikipedia.org/wiki/IFrame"
}
var salModString = "https://en.wikipedia.org/wiki/IFrame" + salModInput";
var serNumPrefString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput";
var bothString = "https://en.wikipedia.org/wiki/IFrame" + serNumPrefInput + salModInput";
document.getElementById('SM_SNPiFrame').src = salModString;
document.getElementById('SM_SNPiFrame').src = serNumPrefString;
document.getElementById('SM_SNPiFrame').src = bothString;
}
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name = "Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame"
width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
I ultimately used this code and it worked:
function filterSelection() {
var smBoxValue = document.getElementById("salModBox").value;
var snpBoxValue = document.getElementById("serNumPrefBox").value;
if (smBoxValue != "" && snpBoxValue != "") {var combinedModString =
"https://example.com/col1=Serial%20Number%20Prefix&op1=EQ&val1=" +
snpBoxValue +"&col2=Sales%20Model%20BOM%20EDS&op2=EQ&val2=" +
smBoxValue";
document.getElementById('SM_SNPiFrame').src = combinedModString;
}
else if (smBoxValue == "" && snpBoxValue != "") {var snpModString =
"https://example.com/#/col1=Serial%20Number%20Prefix&op1=EQ&val1="
+ snpBoxValue;
document.getElementById('SM_SNPiFrame').src = snpModString;
}
else if (smBoxValue != "" && snpBoxValue == "") {var salModString =
"https://example/col1=Sales%20Model%20BOM%20EDS&op1=EQ&val1=" +
smBoxValue;
document.getElementById('SM_SNPiFrame').src = salModString;
}
else {document.getElementById('SM_SNPiFrame').src =
"https://example.com/";
}
}
Your code seems a bit complex than what your issue is, I'll explain to you how to correct this and use some good practices in JavaScript.
Since you need to handle the values inside the input tags and use them into the iFrame tag, we will do the following:
Global elements first.
Since we will probably need to define only once which DOM element is the iFrame tag and which ones are the input tags, lets have them at the very beginning:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
Also, we define a strings variable that will help us store the input values in the same index as elements array.
Set event listeners for every element.
After defining which elements we want to use, now we should handle the change of its value. The most fast-looking effect is to use keyup event, this will pass the value everytime that the user types:
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
In this event listener, you need to setup what will happen every time this event is fired. I just did a simple function to store the new value into the same index but in different array (strings array).
And after that done, call the function that will update the iFrame tag.
Keep your code simple and functional.
The function salModSnpFilter() doesn't need a lot of if statements and the same string appearing multiple times to handle the new source of the iFrame. Lets keep code simple:
const salModSnpFilter = () => {
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/"; //You can set it to empty: "" if you dont want slashes.
strings.forEach(string => {
if (string !== "") {
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
We define the base URL in a variable at the top and a variable that will hold the string that we will append to the base source.
We iterate over the strings array and add this string to finalString array in the same order of the inputs.
After this, the only thing left to do is to set the source of the iFrame tag.
Final code:
var iframe = document.getElementById('SM_SNPiFrame'),
elements = [
document.getElementById('salModBox'),
document.getElementById('serNumPrefBox')
],
strings = [];
elements.forEach((e,index)=>{
e.addEventListener("keyup",event=>{
strings[index] = event.target.value;
salModSnpFilter();
});
});
const salModSnpFilter = () =>{
let source = "https://en.wikipedia.org/wiki/IFrame",
finalString = "/";//You can set it to empty: "" if you dont want slashes.
strings.forEach(string=>{
if(string !== ""){
finalString += string; //You can add a slash with by adding: + "/" between the s and the semicolon.
}
});
iframe.src = source + finalString;
};
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box A" name="Box A" id="salModBox">
</div>
<div>
<input name="textfield" type="text" class="guidedQueryEntry" placeholder="Box B" name="Box B" id="serNumPrefBox">
</div>
<div>
<iframe src="https://en.wikipedia.org/wiki/IFrame" width="100%" height="600" style="border-color:#FFCD11" id="SM_SNPiFrame" allowfullscreen></iframe>
</div>
Note: The order of the strings and how they are used on the iFrame are the same as the order you added the inputs to the elements array. This means, inputA value will always go before inputB value. Unless you change the order in the elements array.

Buttons text not changing in JavaScript?

I'm trying to change the text of a button to that of a value stored in a variable. The button is currently blank and not even using a fixed value like .value = "test"; is working.
HTML:
<div id="addContainer">
<textarea id="listTitleInput" class="textarea" placeholder="Add the title of your list here, then click 'Add List'." rows="10" cols="50"></textarea>
<button id="addListBtn" data-role="button">Add List</button>
</div>
<div id="listDisplayContainer">
</div>
JS:
$(document).ready(function () {
//LISTS
var listTitleInput = document.getElementById("listTitleInput");
var addListBtn = document.getElementById("addListBtn");
var listCount = localStorage.getItem("listCount");
if (listCount === null) {
noteCount = 0;
}
//ADD LISTS
function addList() {
if ($("#listTitleInput").val() == "") {
alert("Please give your list a title, then click 'Add List'.");
} else {
listCount++;
var list = $("#listTitleInput").val();
console.log("List Count: " + listCount);
console.log(list);
var display = document.createElement("button");
document.getElementById("listDisplayContainer").appendChild(display);
display.className = "ui-btn";
display.id = "list" + listCount;
$("#list" + listCount).value = list;
}
}
//Lists
addListBtn.addEventListener("click", addList);
});
Looks like you need to change $("#list" + listCount).value = list; to $("#list" + listCount).text(list);
value is not a property and val() doesn't work for a button.
The problem is that you are confusing native DOM attributes with jQuery ones.
$("#list" + listCount).value = list;
$("#list" + listCount) is a jQuery object so it doesn't use the native javascript properties that you may be used to. (value=)
What you are looking for is:
$("#list" + listCount).html(list);
Or
$("#list" + listCount).text(list);
Since list is a string value, it will be best to use .text

Pull first instance of input and add id via JS

I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Print dynamic Text box value using JQuery

I have a scenario like
for(int i = 0; i < 10; i++)
{
<input type = "text" id="test"+i value="" onchange="getValue(i)">
}
I want to print selected text box value using jquery. I tried below code,....
function getValue(id)
{
var value = $("#test"+id).val();
alert(value);
}
Some how the above code is not working.
if i tried like var value = document.getElementById("test"+id); then it is working.
jsBin demo
var inp = ''; // String will hold all inputs
for(var i=0; i<10; i++){
inp += '<input type="text" id="test'+i+'" value="" />'; // Generate 10 inputs
}
$('body').append( inp ); // All inputs to HTML
$('input[id^="test"]').on('input', function(){
console.log( this.value );
});
You can't just drop raw HTML inside of a JavaScript loop like that. You have to set a string or create an element and append it to the DOM.
"getValue(i)" is a string. The "i" is not the variable i, it is literally a string with the letter i. If you want to concatenate strings and variables you have to do so like this:
var name = "Neil";
var greeting = "Hi, my name is " + name + ", nice to meet you!";

how can concatenate the set variable in a for loop to be use as name in an input to get the value?

how can concatenate the set variable in a for loop to be use as name in an input to get the value?
<script>
var k=0;
var counter = 50;
for(k=0; k<=counter; k++){
var choices = $('input[name=choices'+ k]).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}
alert(choices);
</script>
there are multiple input field namely choices1,choices2 and so on.
how can i get the value of those fields using for loop?
how can i concatenate the name choices and the variable k?
can you help me solve this problem??
You could always just iterate using a specialized attribute selector and .each():
var choices = $('input[name^="choices"]'), // name starts with "choices"
choices_val = [] // an array!
;
choices.each(function () {
choices_val.push($(this).val().replace(/\ /g, '%'));
});
alert(choices_val.join(';'));
It saves you the overhead (and headache) of having to pick out and mangle a specific attribute value (choices1, choices2, etc) and having to select it out via selector ('cause I'd think that selecting via $(this) is faster than $('input[name="choices1"]')).
You're declaring choices three times, which is invalid and will lead to many errors.
You use each in jQuery, it's identical as for loop.
Say for example you have this HTML:
​<input type ="text" name="field1" value="Alpha" />
<input type ="text" name="field2" value="Bravo" />
<input type ="text" name="field3" value="Charlie" />​
And here is the js file:
var k = 1;
$('input').each(function(e) {
alert('choices' + k + '=' + $(this).val());
k++;
});​
Demo here. Hope it helps.
$('input[name=choices'+ k +']').val();
you just forget to put another + sign and single quote.
I think you missed 2 quotes and a +.
$('input[name=choices' + k + ']').val();
add quotes
var choices = $('input[name=choices'+ k + ']').val();
use css selector
$(".className").each(function(){
$(this).myFunction();
})
jQuery.fn.myFunction = function()
var choices = $(this).val();
var choices = choices.replace(/\ /g, '%');
var choices_ = choices_ +";"+ choices;
}

Categories

Resources