Don't append if string already contains OnChange - javascript

I have a javascript OnChange function on a column having textboxes which captures the name of each row in a column. I am appending all the names and storing in variable.
Now , suppose user clicks same textbox again , I don't want to append that name again.
var AppendedString = null;
function onChangeTest(textbox) {
AppendedString = AppendedString;
AppendedString = AppendedString + ';' + textbox.name;
// this gives null;txt_2_4;txt_2_6;txt_3_4;txt_2_4 and so on..and I don't want to append same name again , here it's txt_2_4
}
My Input text :
<input type="text" name="txt_<%=l_profileid %>_<%=l_processstepsequence%>" value="<%= l_comments%>" onfocus="this.oldvalue = this.value;" onchange="onChangeTest(this);this.oldvalue = this.value;">

Those rows seem to have unique names.
you can simply check if AppendedString already contains that name :
var AppendedString=''
function onChangeTest(textbox) {
if (!AppendedString.includes(textbox.name)) {
AppendedString += ';' + textbox.name;
}
}
Codepen Link
You can’t initialize AppendedString as null otherwise, the includes() method won’t be available
otherwise, you can give each row a unique ID, and store in an array IDs that already have been clicked by the user.
var AppendedString = '';
var clickedRows = [];
function onChangeTest(textbox) {
if (!clickedRows.includes(textbox.id)) {
AppendedString += ';' + textbox.name;
clickedRows.push(textbox.id)
}
}

var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!(arr.indexOf(nowS) > -1)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">
Somewhat similar to your need,
var arr = [];
$("input[type='text']").on("click", function() {
var nowS = ($(this).attr('name'));
if (!arr.includes(nowS)) {
arr.push(nowS)
}
console.log(arr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="m1" name="lbl1">
<input type="text" id="m2" name="lbl2">
<input type="text" id="m3" name="lbl3">

You can add flag your textboxes and ignore if it's clicked again. Like using jquery you can do something like this:
function onChangeTest(textbox) {
AppendedString = AppendedString;
if (!textbox.hasClass("clicked")){
AppendedString = AppendedString + ';' + textbox.name;
textbox.AddClass("clicked");
}
}

Related

populate input fields from php / javascript

How can I populate 50 html5 input fields from an external delimited "|" text file ("players.txt"):
Smith, Bob|Jones, James|Cavanaugh, Harvey|
I have input fields like so:
<input type="text" name = "N01" id = "I01">
<input type="text" name = "N02" id = "I02">
<script>
$jQuery.get('assets/players.txt', function(data) {
splitString = dataString.split("|");
$('#I01').val(splitString[0]);
$('#I02').val(splitString[1]);
$('#I03').val(splitString[2]);
});
</script>
Try getting html elements using jquery $ sign such as
$('#I01').val(splitString[0]);
$('#I02').val(splitString[1]);
$('#I03').val(splitString[2]);
You're currently referencing the wrong data variable dataString, instead reference data. Also, if you know your IDs are sequential, you can avoid writing 50 different lines of JS and run a for loop, for instance:
for(i=0; i<splitString.length; i++){
id = "#I0"+(i+1);
$(id).val(splitString[i]);
}
Don't set the value of each element individually, use a forEach loop.
Make sure to take into account string padding.
splitString.forEach((str, i) => {
document.querySelector('#I' + String(i).padStart(2, '0'))
.value = str;
});
let dataString = "Smith, Bob|Jones, James|Cavanaugh, Harvey|";
let splitString = dataString.split("|");
for (let i = 0; i < splitString.length; i++) {
$("#I0" + i).val(splitString[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="N01" id="I01">
<input type="text" name="N02" id="I02">
Example without ajax:
$(function(){
var splitString = 'Smith, Bob|Jones, James|Cavanaugh, Harvey';
splitString = splitString.split("|");
$('#playersInputs').empty();
$.each(splitString, function(i,v){
$('<input type="text" />')
.attr('name', 'N'+("0"+(i+1)).slice(-2))
.attr('id', 'I'+("0"+(i+1)).slice(-2))
.val(v)
.appendTo('#playersInputs');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='playersInputs'>
</div>
Example With ajax:
you must replace /path/to/your/text-file with the actual url
$(function(){
$.get('/path/to/your/text-file', function(data) {
var splitString = data.split("|");
$('#playersInputs').empty();
$.each(splitString, function(i,v){
$('<input type="text" />')
.attr('name', 'N'+("0"+(i+1)).slice(-2))
.attr('id', 'I'+("0"+(i+1)).slice(-2))
.val(v)
.appendTo('#playersInputs');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='playersInputs'>
</div>

How can I change a part of input's name via jquery?

I have such code in my view:
<div class="box">
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
</div>
In my js I'd like to change [1] into [2] or [3] and so on after [quantity], depending on how many additional forms I create. How can I do that?
This is what I have in my JS:
var i = 1
$('.add_another_price_btn').click( function (e) {
e.preventDefault();
$(this).prev().clone().insertBefore($(this));
$(this).prev().find('.remove_another_price_btn').show();
$(this).prev().find('.product_quantity').removeAttr('readonly');
$(this).prev().find('.product_quantity').attr('value', '');
//This is what I tried, but it doesn't work properly.
$(this).prev().find('.product_quantity')
.attr('name', function() { return $(this).attr('name') + '['+ (i++) + ']' });
$('.remove_another_price_btn').click( function (ee) {
ee.preventDefault();
$(this).parent().parent().remove();
});
You can do a simple string operation with substr and lastIndexOf to replace the last part of the name.
// get input and name of input
var input = $("input");
var name = input.attr("name");
// change just the last part
name = name.substr(0, name.lastIndexOf("[")) + "[2]";
// set name back to input
input.attr("name", name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="product[size_ids][<%= size.id %>][quantity][1]" readonly class="product_quantity" placeholder="quantity from" value="1">
Save the clone
Break the name using substring or split and parseInt
Like this
var $clone = $(this).prev().clone(),
$prodQ = $clone.find('.product_quantity'),
name = $prodQ.attr("name"),
parts = name.split("quantity]["),
newName = parts[0]+"quantity][",
num = parseInt(parts[1],10); // or a counter
num++;
newName += num+"]";
$prodQ.removeAttr('readonly').attr('value', '').attr('name',newName);
$clone.insertBefore($(this));
$clone.find('.remove_another_price_btn').show();

dynamic name for an input with jQuery

I have an issue with automatic name for input, I'll try to explain what i need to do. i have an id, that I get it from an external function. I need to use this numeric id to create another function like that.
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
When I try to do that I get undefined, but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. Please help me figure out how to solve this problem.
Did you want something like this? This is based on an assumption that you have checkboxes within a form!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
use this code no need for id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
here is the fiddle
https://jsfiddle.net/rrehan/srhjwrz4/
Try below code:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
Demo Link

Pass generated string as variables in javascript function

This is my html:
<form>
<input type='text' name='campo1' value='valor0'/>
<input type='text' name='campo2' value='valor1'/>
<input type='text' name='campo3' value='valor2'/>
<input type='text' name='campo4' value='valor3'/>
<input type='text' name='campo5' value='valor4'/>
<input type='text' name='campo6' value='valor5'/>
<input type="button" onclick="inpt();">
</form>
I created a function to make a string and pass it to another function
The string contain all values for input text with match string 'campos' in the input name.
<script type="text/javascript">
var tags_inpt = new Array();
var param = "";;
function inpt() {
tags_inpt=document.getElementsByTagName('input');
var i;
for (i=0; i<tags_inpt.length; i++) {
if ((tags_inpt[i].type=='text')&&(tags_inpt[i].name.match(/campo/))){
param += '"' +tags_inpt[i].value +'",';
}
}
alert(param + '"A"'); // this print -> "valor0","valor1","valor2","valor3","valor4","valor5","A" OK!!
// call funcion2()
funcion2("valor0","valor1","valor2","valor3","valor4","valor5","A"); // this result in valor1 in funcion2() OK!!
funcion2(param + '"A"'); // this return 'undefined' --> BAD
}
function funcion2(a,b,c,d,e,f,g){
var z = b;
alert (z);
}
</script>
When use param variable to dynamically pass arguments to funcion2(), I get undefined value.
What is the correct way to make this?
Thanks
Try this:
funcion2.apply(window, (param + ',"A"').split(",") );
See the DEMO
Don't use string concatenation for this, that's prone to errors depending on your input. Use an array instead:
<script type="text/javascript">
function inpt() {
var tags_inpt = document.getElementsByTagName('input');
var matches = [];
for (var i=0; i<tags_inpt.length; ++i) {
if ((tags_inpt[i].type=='text') && (tags_inpt[i].name.match(/campo/))){
matches.push(tags_inpt[i].value);
}
}
matches.push('A');
funcion2.apply(this, matches);
}
function funcion2(a,b,c,d,e,f,g) {
var z = b;
alert (z);
}
</script>

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories