Set value to input by calling javascript function - javascript

I am inserting a list of inputs through php loop.
For each input I need to get the value from database via ajax, For that I need to call a javascript function. I am not sure if it possible.
I am looking for something like this
<input ... value="javascript:getvalue(id)">
<script>
function getvalue(id) {
//set the value fron here
}
</script>

value attr just accepts strings more here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value.
You can use data-attributes or an id to assign the id and then get the value for it after its loaded.
Please check the below snippet
<input data-id="id1">
<input data-id="id2">
<input data-id="id3">
<script>
(function(){
var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++) {
inputs[i].value = getvalue(inputs[i].dataset["id"])
}
}())
function getvalue(id) {
return id;
}
</script>

$(document).ready(function(){
for(let i=0; i< $('.frmDatabase').length; i++) {
getvalue($('.frmDatabase').eq(i).attr('id'));
}
})
function getvalue(id) {
//ajax call
//set async false and in success bind value from db to id
$('#' + id).val(1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="txtTest1" class="frmDatabase">
<input id="txtTest2" class="frmDatabase">

Related

Loop data fetched from val()

I am trying to get some data from a hidden element and loop through it and have it in an array.
The element looks like this:
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any""}]'>
Now when I grab this with jquery:
$(document).ready(function () {
var data = $(".test").val();
console.log(data);
//test loop
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
But it loops through every character instead of each {} in [].
What am I missing?
JS Bin for reference: https://jsbin.com/madaquyepa/edit?html,js,console,output
When you retrieve the input element's value, it is a string (a JSON actually). So, you will need to pass it through JSON.parse() first.
Note: there is an extraneous " near the very end of the string, which will cause an error if you try to parse it. Remember to fix it first.
$(document).ready(function() {
var data = JSON.parse($(".test").val());
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>
For an ES6 version that doesn't even use jQuery:
const data = JSON.parse(document.querySelector('.test').value);
console.log(data);
for (let datum of data) {
console.log(datum);
}
<input class="test" type="hidden" name="fwrls" value='[{"comment":"test1","policy":"deny","proto":"any"},{"comment":"test2","policy":"allow","proto":"any"}]'>

Undefined result in Console by Input to Array Fields

Why when I pus the Submit button is undefined all of them?
I want to create an array just by using input fields like this.
Is there a nother way to do this?
I tried to do it with Class name and the result is still undefined
function clicked() {
var input_value = document.querySelectorAll('#data, #data1, #data2, #data3, #data4').value;
console.log(input_value)
}
document.getElementById('btn').addEventListener('click', clicked);
<input id="data">
<input id="data1">
<input id="data2">
<input id="data3">
<input id="data4">
<button id="btn">Click me</button>
querySelectorAll will return a "NodeList", which is similar to an array. NodeLists don't have a value property, so it's returning undefined.
If you want to get the value from each of the input boxes, you'll need to loop through the NodeList and pull the value from each HTML element individually.
function clicked() {
var nodeList = document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
for (var i = 0; i < nodeList.length; i++) {
console.log(nodeList[i].value);
}
}
document.getElementById('btn').addEventListener('click', clicked);
Change fn to this:
function clicked() {
var inputs= document.querySelectorAll('#data, #data1, #data2, #data3, #data4');
inputs.forEach(i => {
console.log(i.value);
});
}

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

jQuery get input val() from $("input") array

I have a function that returns whether or not every text input in a form has a value.
When I first made the function it looked like this:
function checkInput(inputId) {
check = 0; //should be 0 if all inputs are filled out
for (var i=0; i < arguments.length; i++) { // get all of the arguments (input ids) to check
var iVal = $("#"+arguments[i]).val();
if(iVal !== '' && iVal !== null) {
$("#"+arguments[i]).removeClass('input-error');
}
else {
$("#"+arguments[i]).addClass('input-error');
$("#"+arguments[i]).focus(function(){
$("input").removeClass('input-error');
$("#"+arguments[i]).off('focus');
});
check++;
}
}
if(check > 0) {
return false; // at least one input doesn't have a value
}
else {
return true; // all inputs have values
}
}
This worked fine, but when I called the function I would have to include (as an arstrong textgument) the id of every input I wanted to be checked: checkInput('input1','input2','input3').
Now I am trying to have my function check every input on the page without having to include every input id.
This is what I have so far:
function checkInput() {
var inputs = $("input");
check = 0;
for (var i=0; i < inputs.size(); i++) {
var iVal = inputs[i].val();
if(iVal !== '' && iVal !== null) {
inputs[i].removeClass('input-error');
}
else {
inputs[i].addClass('input-error');
inputs[i].focus(function(){
$("input").removeClass('input-error');
inputs[i].off('focus');
});
check++;
}
}
if(check > 0) {
return false;
}
else {
return true;
}
}
When I call the function it returns this error:
Uncaught TypeError: inputs[i].val is not a function
What am I doing wrong?
When you do inputs[i], this returns an html element, so it is no longer a jquery object. This is why it no longer has that function.
Try wrapping it with $() like $(inputs[i]) to get the jquery object, and then call .val() like:
$(inputs[i]).val()
If you are going to use this in your for loop, just set it as a variable:
var $my_input = $(inputs[i])
Then continue to use it within the loop with your other methods:
$my_input.val()
$my_input.addClass()
etc..
if you use jquery .each() function, you can do it a little cleaner:
$(document).ready(function() {
$('.submit').on('click', function() {
$('input').each(function() {
console.log('what up');
if($(this).val().length < 1 ) {
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
.input-error {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<br/>
SUBMIT
This is actually a very simple fix. You need to wrap you jquery objects within the jquery constructor $()
Such as for inputs[i].val() to $(inputs[i]).val();
Here is the full working example:
http://jsbin.com/sipotenamo/1/edit?html,js,output
Hope that helps!
This is exactly one of the things the .eq() method is for. Rather than using inputs[i], use the following:
// Reduce the set of matched elements to the one at the specified index.
inputs.eq(i)
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
in this case, I would make use of the jQuery.each() function for looping through the form elements. This will be the modified code
function checkInput() {
var $inputs = $("input"),
check = 0;
$inputs.each(function () {
val = $.trim($(this).val());
if (val) {
$(this).removeClass('input-error');
}
else {
$(this).addClass('input-error');
$(this).focus(function () {
$("input").removeClass('input-error');
$(this).off('focus');
});
check++;
}
});
return check == 0;
}

How to pass an array created in javascript to another jsp and then use that array in a java function on that jsp?

Here is a script i have and I want to be able to pass the array "playernames" into a java function on another .jsp. I'm wonder how to pass that array to another page and then retrieve it for my java function.
<script>
function getPlayerNames() {
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
}
</script>
Edit:
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<input type="hidden" id="players" />
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").values=playernames;
document.getElementById("players").submit();
window.location.replace("lineups.jsp");
}</script>
Other jsp
<%String[] players = request.getParameterValues("players");%>
You'll need to have the hidden field inside the form tags with the id and action attributes set as below.
<td style="vertical-align: top;"><button onclick="getPlayerNames()"id="generate">Generate</button><br></td>
<form id="playerNames" action="Url"> // In action give the Url of the jsp page you want to send the values to lineups.jsp in your case I guess.
<input type="hidden" id="players" name="players" />
</form>
<script>
function getPlayerNames(){
var selected = document.querySelectorAll("#selected-players > tr > td");
var playernames = [];
for(var i=0; i<selected.length; ++i){
var id = selected[i].getAttribute('id');
if (id.indexOf('Player')>-1) {
playernames.push(selected[i].textContent);
}
}
document.getElementById("players").value=playernames;
document.getElementById("playerNames").submit();
}</script>
1) Stringify the array and then assign to hidden field.
Refer: Javascript Hidden Input Array
2) Submit the hidden field in a form to server.
<input type="hidden" id="hiddenArrayField"/>
document.getElementById("hiddenArrayField").value=yourStringifyArrayValue;
3) On server you would get this as a part of request i.e. on next jsp you can retrieve this value as a request parameter.
<%= request.getParameter("hiddenArrayField")%>

Categories