Finding last entered input - javascript

<div class="input-group">
<input type="password" maxlength="1" value="1" readonly="">
<input type="password" maxlength="1" value="2" readonly="">
<input type="password" maxlength="1" value="3" readonly="">
<input type="password" maxlength="1" value="" readonly="">
</div>
I'm trying to get the last entered input:
document.querySelector('.input-pin input[value!=""]:last-child')
... so last-child of input with value not empty, but its an invalid selector.

If you want to base the selection on the attribute value, then you could use the :not() pseudo class to negate the input element with an empty value.
In this case the selector would be:
input[value]:not([value=""])
From there, you can select all the matching elements and retrieve the last one:
var inputs = document.querySelectorAll('input[value]:not([value=""])');
var lastInputWithValue = inputs[inputs.length - 1];
...or:
var inputs = document.querySelectorAll('input[value]:not([value=""])');
var lastInputWithValue = Array.from(inputs).pop();
If the value can change and you want to check based on current property value (rather than the attribute value), then you would need to filter the elements:
var inputs = document.querySelectorAll('input');
var lastInputWithValue = Array.from(inputs).filter(i => i.value).pop();
As a side note, the :last-child pseudo class will only return the last child element inside of the parent element based on their order. It will not filter the selected elements and select the last one by their attribute or class as you are expecting. Also, [value!=""] is not a valid attribute selector as you pointed out. However, you can use input[value]:not([value=""]) like I pointed out above.

You could simply do document.querySelector('.input-group input:last-child');

Related

Output Contents of Input in div

I am creating a contact form that creates something like a cart view depending on the inputs.
I managed to get all the checkboxes to output when they are checked; I am having trouble getting the same to work with text and number inputs. So input type text, number and textarea.
<input id="form_name" type="text" name="name" class="form-control"
placeholder="Please enter your firstname *" required="required"
data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99"
class="form-control" required="required"
data-error="Pflichtfeld" data-validate="true">
<div id="descript11" style="display:none;">Vorname:
<b id="vorname"></b>
</div>
<div id="descript12" style="display:none;">Alter:
<b id="alter"></b>
</div>
So I tried the method with $(document).change() but that did not work. I want to grab the contents of the input or textarea and output it to the div with the corresponding id. So "age" should output to "alter" and so on. I'm not sure how to achieve this and w3schools or other sites don't offer an answer.
You can do this by adding an input event listener to your input text boxes. In the example below, I loop through all your input text boxes (as I gave them a class of text-input) using a forEach loop. You can then grab the text from the textbox using this.value and place it into its associated div. To help with this I created a mapping object which is used to map the id of the input to the id of where the text should be placed into.
See example below:
const input_map = {
form_name: "vorname",
age: "alter"
}
document.querySelectorAll(".text-input").forEach(elem => {
elem.addEventListener('input', function() {
const textbox_value = this.value; // get text from input bpx
const target = input_map[this.id]; // get location (ie: the id) of where the text should be placed
document.getElementById(target).innerText = textbox_value; // place the text in that location
});
});
<input id="form_name" type="text" name="name" class="form-control text-input" placeholder="Please enter your firstname *" required="required" data-error="Pflichtfeld" data-validate="true">
<input type="number" id="age" name="age" min="16" max="99" class="form-control text-input" required="required" data-error="Pflichtfeld" data-validate="true">
<div id="descript11">Vorname:<b id="vorname"></b></div>
<div id="descript12">Alter: <b id="alter"></b></div>
Note: In the example above I removed the style="display: none;" from your divs so that you can see the output
You can do it like this:
$('input').on('input',function(){
let text = $(this).val();
let id = $(this).attr('id');
$('div.'+id).text(text)
});
This snippet checks changes on inputs and sets their value to the div with class that matches each input's id .

Disabling textarea and input at the same time

I disable a textarea like in this code snippet:
function toggleDisabled(_checked,id) {
document.getElementById(id).readOnly = !_checked;
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked,'new_order')">
<textarea name="noa" id="new_order">FOOO</textarea>
<input type="text" name="noo" id="new_order">
Now I want input text to get disabled when I check the checkbox. So that both textarea and input:text will be disabled.
I tried to add the id that I used as ID for textarea but input:text and textarea are conflicted since readOnly is only for textarea.
So that I need a way tp say if textarea disable like this... , if input disable like this ...
id must be unique! Never use same id to more than one element.
the code below selects all elements that have the class new_order and then iterate through then disabling or enabling then. Take a look
function toggleDisabled(self) {
var inputs = document.getElementsByClassName('new_order');
for (var i = 0; i < inputs.length; i++){
inputs[i].disabled = self.checked;
}
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this)">
<textarea name="noa" class="new_order">FOOO</textarea>
<input type="text" name="noo" class="new_order">
The problem arises when you use an id multiple times... ID's are supposed to be unique. If you use classes it should work:
function toggleDisabled(_checked, selector) {
document.querySelectorAll(selector).forEach((el) => {
el.readOnly = _checked;
});
}
<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked,'.new_order')">
<textarea name="noa" class="new_order">FOOO</textarea>
<input type="text" name="noo" class="new_order">

Create dynamic name of newly appended child

I have the following form inputs in a particular td tag.
<input type="text" value="" name="form_data[1][1][text]"><br>
<input type="text" value="" name="form_data[1][2][text]"><br>
<input type="text" value="" name="form_data[1][3][text]"><br>
Also I have the code for appending new form. But i need to change its name like this form_data[1][4][text] that is array name with next index for text should come.
i.e.
<input type="text" value="" name="form_data[1][4][text]"><br>
Add a class to your input, get the number of elements with this class:
var nbElt = document.getElementsByClassName('yourclass').length;
var newInp = document.createElement('input');
newInp.name = "form_data[1]["+parseInt(nbElt+1)+"][text]";
document.body.appendChild(newImp);
And it's done.

Replicating the values to another textbox

I have a question regarding JSP. I have two textboxes. When I type the value in the first text box, it should replicate automatically in the second text box.
<input type="text"
class="formtext"
name="List.lItemList<c:out value='[${status.index}]'/>.value1"
value="0.0"
onChange="validateOnChange(this,'desc','minvalue','maxValue','float')">
<input type="text"
class="formtext"
name="List.clItemList<c:out value='[${status.index}]'/>.value2"
value="0.0"
onChange="validateOnChange(this,'desc','minvalue','maxvalue','float')">
Assuming that the first box has ID input1 and the second input2 (so you'll have to add those IDs), you can do it like this:
document.getElementById('input1').onkeyup = function () {
document.getElementById('input2').value = this.value;
};
You can do this using JavaScript. Attach an keyup event handler on the first textbox which should copy its value to the second one.
<input type="text" id="t1" onkeyup="document.getElementById('t2').value=this.value" />
<input type="text" id="t2" />

How to get an Array with jQuery, multiple <input> with the same name

I have a form where users can add input fields with jQuery.
<input type="text" id="task" name="task[]" />
After submitting the form I get an array in PHP.
I want to handle this with the $.ajax() but I have no idea how to turn my <input>s to an array in jQuery.
Using map:
var values = $("input[id='task']")
.map(function(){return $(this).val();}).get();
If you change or remove the id (which should be unique), you may also use the selector $("input[name='task\\[\\]']")
Working example: http://jsbin.com/ixeze3
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.
You could just remove the id attribute and and replace it with:
<input type='text' name='task'>
and to get an array of the values of task do
var taskArray = new Array();
$("input[name=task]").each(function() {
taskArray.push($(this).val());
});
To catch the names array, i use that:
$("input[name*='task']")
You can't use same id for multiple elements in a document. Keep the ids different and name same for the elements.
<input type="text" id="task1" name="task" />
<input type="text" id="task2" name="task" />
<input type="text" id="task3" name="task" />
<input type="text" id="task4" name="task" />
<input type="text" id="task5" name="task" />
var newArray = new Array();
$("input:text[name=task]").each(function(){
newArray.push($(this));
});
HTML:
<input type="text" name="task[]" class="form-control" id="task">
JS:
var tasks= new Array();
$('input[name^="task"]').each(function()
{
tasks.push($(this).val());
});
if you want selector get the same id, useļ¼š
$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
You can use jquery.serializeJSON to do this.
Q:How to access name array text field
<input type="text" id="task" name="task[]" />
Answer - Using Input name array :
$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()

Categories

Resources