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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.