variables in loop for cycle with javascript - javascript

I simplify my problem to a minimum because in reality my code is very long and complex to explain.
I have two text input fields, in the first field I can insert a series of values, while the second field receives the values of the first field and compares them with those it already has. if there are double values the function warns and the user can choose whether to overwrite them or delete them, otherwise the value is added.
I want to do this through a for loop.
function prova() {
var stringa_valoredainserire = document.getElementById("valoredainserire").value;
var stringa_valoredacambiare = document.getElementById("valoredacambiare").value;
var stringa_valoredacambiare2 = document.getElementById("valoredacambiare");
mioarray = stringa_valoredainserire.split("; ");
var i, len, text;
//inizio ciclo for
for (i = 0, len = mioarray.length, text = ""; i < len; i++) {
if (stringa_valoredacambiare.indexOf(mioarray[i]) !== -1) {
if (confirm('il valore ' + mioarray[i] + ' esiste, ok per sovrascriverlo, annulla per cancellarlo')) {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i], mioarray[i]);
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare.replace(mioarray[i] + '; ', '');
}
} else {
stringa_valoredacambiare2.value = stringa_valoredacambiare2.value + mioarray[i] + '; ';
}
}
}
<input id="valoredainserire" value="" type="text">
<input id="valoredacambiare" value="pere; cipolle; mele; " type="text" readonly>
<input type="button" onclick="prova();" value="Prova">
the problem is that if the values to be entered in the first input field are equal to the values of the second, if I wanted to delete them, the function only deletes the last one, because it is the last variable that keeps it in memory.
how can I remedy this situation? some idea? Thanks in advance.

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.

javascript capture every value in a div

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"

How do i rearrange the number in java script loop?

I have done the dynamic generates textbox based on the number that user type. For example, user types 10 in the input box clicked add will generate 10 input box. I have a label to catch the number.
here is my question
how do I start from 1?
how do I rearrange the number when user remove one of the input boxes
here is my javascript
$(document).ready(function () {
$("#payment_term").change(function () {
var count = $("#holder input").size();
var requested = parseInt($("#payment_term").val(), 10);
if (requested > count) {
for (i = count; i < requested; i++) {
$("#payment_term_area").append('<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label>' + i + 'Payment</label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
$("#payment_term_area").on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
calculateTotal();
x--;
})
}
});
});
here is my view
<input type="text" id="payment_term" />
<button onclick="function()">Add</button>
<div id="payment_term_area"></div>
You were nearly there, however, by hardcoding the label's you were making updating them difficult for yourself. I have created a jsfiddle of my solution to your problems. I personally prefer to cache the values of my jQuery objects so that they arent hitting the DOM each time they are referenced, for the performance boost (hence why they are listed at the top). I also, find it nicer to bind the click event in JS rather than using the html attribute onclick, but this is just a preference.
JSFIDDLE
Javascript
// create cache of jQuery objects
var add_payment_terms_button = $('#add_payment_terms');
var payment_term_input = $('#payment_term');
var payment_term_area = $('#payment_term_area');
var default_payment_values = ['first value', 'second value', 'third value', 'forth value', 'fifth value'];
var default_other_value = 'default value';
// bind to generate button
add_payment_terms_button.on('click', generatePaymentTerms);
function generatePaymentTerms(){
var requested = parseInt(payment_term_input.val(), 10);
// start i at 1 so that our label text starts at 1
for (i = 1; i <= requested; i++) {
// use data-text to hold the appended text to the label index
payment_term_area.append(
'<div class="col-lg-12 product_wrapper">' +
'<div class="col-lg-12 form-group">' +
'<label data-text=" Payment"></label>' +
'<input type="text" class="payment_term form-control" name="PaymentTerm[]"/>' +
'</div>' +
'cancel' +
'</div>');
}
// call the function to set the labels
updateProductIndexes();
}
function updateProductIndexes(){
// get all labels inside the payment_term_area
var paymentLabels = payment_term_area.find('.product_wrapper label');
for(var x = 0, len = paymentLabels.length; x < len; x++){
// create jQuery object of labels
var label = $(paymentLabels[x]);
// set label text based upon found index + 1 and label data text
label.text( getOrdinal(x + 1) + label.data('text'));
// either set the next input's value to its corresponding default value (will override set values by the user)
label.next('input.payment_term').val(default_payment_values[x] || default_other_value)
// or optionally, if value is not equal to blank or a default value, do not override (will persist user values)
/* var nextInput = label.next('input.payment_term');
var nextInputValue = nextInput.val();
if(nextInputValue === '' || default_payment_values.indexOf(nextInputValue) >= 0 || nextInputValue === default_other_value){
nextInput.val(default_payment_values[x] || default_other_value)
} */
}
}
// courtesy of https://gist.github.com/jlbruno/1535691
var getOrdinal = function(number) {
var ordinals = ["th","st","nd","rd"],
value = number % 100;
return number + ( ordinals[(value-20) % 10] || ordinals[value] || ordinals[0] );
}
payment_term_area.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('.product_wrapper').remove();
// after we remove an item, update the labels
updateProductIndexes();
})
HTML
<input type="text" id="payment_term" />
<button id="add_payment_terms">Add</button>
<div id="payment_term_area"></div>
First you have to give id for each label tag ex:<label id='i'>
Then you can re-arrange the number by using document.getElementById('i')
Refer the Change label text using Javascript
hope this will be much helpful

Add/Remove value to input on click

i have this code that i use, and on click i put email in field, but what i want to accomplish is that on next click on same field it removes email if one already exist in input.
Here is my code:
<p class="email">mail1#gmail.com</p>
<p class="email">something#gmail.com</p>
<p class="email">third#gmail.com</p>
<input type="text" id="contact-email" value="" class="form-control" style="width:500px" />
And js:
var $contact = $('#contact-email');
$('.email').on('click', function () {
if ($contact.val()) {
$contact.val($contact.val() +'; '+ $(this).text());
} else {
$contact.val($(this).text());
}
});
and fiddle https://jsfiddle.net/2dffwew5/2/
I would store selected email addresses to an array. Then push or splice the clicked email.
var $contact = $('#contact-email');
var emails = [];
$('.email').on('click', function () {
var index = emails.indexOf($(this).text());
if (index > -1) {
emails.splice(index, 1);
} else {
emails.push($(this).text());
}
$contact.val(emails.join(";"));
});
https://jsfiddle.net/jdgiotta/ze7zebzq/
I would suggest that you add a check to see if the current text contains the selected email address. If it does, then remove it. Otherwise add it.
You will also need to cater for leading/trailing dividers, which can easily be done with a couple of conditional checks.
Something like this:
var $contact = $('#contact-email');
$('.email').on('click', function () {
var text = $(this).text(); // Get the value to insert/remove.
var current = $contact.val(); // Get the current data.
// Check if the value already exists with leading seperator, if so remove it.
if (current.indexOf('; ' + text) > -1) {
$contact.val(current.replace('; ' + text, ''));
}
// Check if the value already exists with trainling seperator, if so remove it.
else if (current.indexOf(text + '; ') > -1) {
$contact.val(current.replace(text + '; ', ''));
}
// Check if the value already exists with no seperator (on it's own), if so remove it.
else if (current.indexOf(text) > -1) {
$contact.val(current.replace(text, ''));
}
// Otheriwse, it doesn't exist so add it.
else {
if (current) {
$contact.val(current + '; ' + text);
} else {
$contact.val(text);
}
}
});
Here is a working example

Displaying multiple html text box values in an ascending order [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model

Categories

Resources