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>
Related
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");
}
}
I want to learn, can we find the same number in two input values.
For example:
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
JS
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
});
});
When onClick event on the .click button then check the same number in the #multinumber and #justonenumber input values and get the result in an alert box.
Is there a way to do this ? Anyone can help me here please?
Just use indexOf or includes on your multiple string. :)
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
As per the problem explained in the comment, it seems the requirement does involve splitting the array.
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val().split(',');
var single = $("#justonenumber").val();
var doesMultipleIncludeSingle = multiple.includes(single);
// OR
var doesMultipleIncludeSingle = multiple.indexOf(single) > -1;
});
});
You can get the value of first input box. Split it by , and check with .indexOf for the other input. If it's there, you can put the result in alert box like
$(".click").click(function(){
var x = $("#multinumber").val().split(",");
var y = $("#justonenumber").val();
if(x.indexOf(y) > 0){
alert(x.find(o=> o==y))
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="multinumber" value="1,2,3,4,5">
<input type="hidden" id="justonenumber" value="3">
<div class="click">Click and test the same number</div>
is this what you want?
$(document).ready(function(){
$("body").on("click",".click", function(){
var multiple = $("#multinumber").val();
var single = $("#justonenumber").val();
if(multiple.indexOf(single) > -1) alert(single + " is found");
else alert(single + " isn't found");
});
});
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();
I want input to enter value number
and When entering the value will be create html node with input inside it
ex
<input>
and when enter value like 3
it will apper
<div><input id='input1-3'><input id='input1-3'><input id='input1-3'></div>
<div><input id='input2-3'><input id='input2-3'><input id='input2-3'></div>
thanx
try this i think it will help you ,
<body>
<input type="text" id='inputnum'>
</body>
jquery,
$(document).ready(function(){
$('#inputnum').on('change',function(){
var a=parseInt($(this).val());
console.log(a);
for(var i=1;i<a+1;i++)
{
var divs='<div>'
for(var j=1;j<a+1;j++)
{
divs=divs+'<input id="input'+i+'-'+j+'">';
}
divs=divs+'</div>';
$('body').append(divs);
}
})
});
Complete JSFiddle Example https://jsfiddle.net/Praveent696/7bt74fbj/
If I correctly understand what you want to do, i think that you just have to use append function like this.
<input id="input1">
<script>
$(document).on("keypress", "input#input1", function() {
var n = this.value;
for (var i=0;i<n;i++){
var x = document.createElement("input");
x.setAttribute("id", "wathever");
document.body.appendChild(x);
}
});
</script>
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)
});