How to update a field on .focusout()? - javascript

I would like, upon loosing focus on an <input> field, to perform a few operations on the value of this field, including changing the content itself (so that it is uppercase)
In the following code:
HTML
<input id="name" type="text"></input>
<div id="upper"></div>
JavaScript + jQuery
$("#name")
.focusout(function() {
// get the text from the form which lost focus
name = $("#name").val();
// turn it into uppercase
name = name.toUpperCase();
// update the form and another entry
$("#upper").text(name);
$("#name").text(name);
})
the event is correctly caught and the <div> is updated with the lowercase text. The content of the field, however, is not updated.
Is it possible to update the content of an <input> field upon leaving it?

Change text() to val() for field
$("#name").val(name);

Use jQuery.val() to set the Value, not jQuery.text(), also note this in handler-function refers to Element on which event is invoked hence this could be used instead of specified-selector
You could try this simplified code:
$("#name").focusout(function() {
var name = this.value.toUpperCase();
$("#upper").text(name);
$(this).val(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="name" type="text"></input>
<div id="upper"></div>

Related

How can I force a user to fill in input fields successively?

I am looking to create an input form that will force a user to enter something in each field successively before moving onto the next input or submitting. This is something that would be filled out by someone on a phone who is asking questions that are attached to each input field and recording the answer in the inputs. Thus to prevent someone from skipping/missing a question while on the phone, I want to require that each input field is filled out successively. For this reason, the HTML 'required' attribute does not necessarily work as it will only prevent submission if a field is not filled out.
Previously I have given each required input its own submit button, but this looks horrible and can be confusing for those who use it. What is the best way to achieve what I am looking do to using a combination of html, js, node, and/or ejs?
Give each input a change event handler that makes the next input visible:
// Get all the labels into a node list
const labels = document.querySelectorAll("label");
// Get a reference to the last label
const lastLabel = labels[labels.length-1];
// Get a reference to a verification element
const output = document.querySelector("div.hidden");
// Use event delegation to handle all change events
document.addEventListener("change", function(event){
// Get reference to the parent label of the changed element
const lbl = event.target.closest("label");
// Check to see if it's an element we care to handle
if(lbl.classList.contains("response")){
// Hide the changed label (and it's child input)
lbl.classList.add("hidden");
// Unhide the next label (and it's input child)
lbl.nextElementSibling.classList.remove("hidden");
}
// If the current label was the last one
if(lbl === lastLabel){
// Show the verification field
output.classList.remove("hidden")
}
});
.hidden { display:none; }
<label class="response">#1<input ></label>
<label class="response hidden">#2<input ></label>
<label class="response hidden">#3<input ></label>
<div class="hidden">DONE!</div>

Resize input field according to already entered input

Alright for some reason I need to have an input field, which fills when a checkbox is ticked. The input field takes the value of the checkbox as input. After that I need to put the value in another input field which is readonly and is styled to NOT look like input (don't ask), but if the value is longer than the field, the text is partially shown.
Now I have seen some code, which helps in similar situations like here, but it helps only when text is entered in the field. I need it to change according to the already entered value.
I have this:
<input type="checkbox" id="single_room" value="Single room"/>
<input type="text" name="single_room_input" id="single_room_input" style="display: none;">
The value is then submitted and processed with php and displayed again in the other input field:
<span class="text">
{$single_room_input}
</span>
<input class="overview-data" name="single_room_input" value="{$single_room_input}" readonly>
and if I use
$(function () {
$('.overview-data').on('input', function ()
{ $('.text').text($('.overview-data').val()); });
});
It does not resize the input field unless you actually input something in.
If someone can please tell me if it is possible and if yes - how to do what I need to do I would be rally grateful.
So if I understand it correctly you have a checkbox that contains a value. When you click that checkbox an input field is filled with the value of the checkbox and also another READONLY input field is filled with that same value?
You could just do the following then:
$(document).on("click", "#single-room", function() {
var checkboxValue = $(this).val();
$("#single-room-input").val(checkboxValue);
$("#your second input field id").val(checkboxValue)
//then do .css to style the length
});

jQuery, detecting actual input text value

I'm running into an issue where the value grabbed by jQuery, and what's actually in the input text field, are different.
A form with a variety of inputs are populated when the page loads with information from our database. Thus, the input text fields all have a value.
When the form is submitted, I have a function that runs first to check for text inputs. This is a portion of that function:
$("form#accountSettingsForm input").each(function(){
var input = $(this);
var value = input.attr("value");
}
Lets say the input value is 12 when the page had initially loaded. If I delete the 12 in the textbox and leave the field blank, and submit the form, the above code retrieved "value" is still 12, not empty.
How can I detect what's actually the textbox's value? Thanks in advance.
This is a situation where there's a difference between the value attribute and the value property. The attribute comes from the HTML, the property is from the dynamic state of the DOM. To get the current value of an input after the user has modified it, use the jQuery .val() method.
$("#accountSettingsForm").submit(function() {
$(this).find("input").each(function() {
var input = $(this);
var value = input.val();
console.log(this.name + " = " + value);
});
return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="accountSettingsForm">
Input 1:
<input name="field1" type="text">
<br>Input 2:
<input name="field2" type="text">
<br>
<input name="submit" type="submit">
</form>
The following appears to work well. If you want to regularly remember/store the value, register for the on('input') event. With this, you get an event every time the user types in the textbox:
$("#accountSettingsForm :input").on('input', function() {
console.log($(this).val());
});
As far as I can tell, the $(this).val() method of access works fine.
Here's a JSFiddle: https://jsfiddle.net/uz8k7rjp/
And the original post where I got this method: JQuery: detect change in input field

filter() arguments not giving correct output

My problem today could be rather simple. I am trying to obtain all required elements inside of a form for which there is no text (they are of type input, text). Here is my JS:
var inputs = $('#form').find(':input');
if(inputs.filter('[required] [value=""]').first().focus().length)
//do something
This is the element in the HTML:
<input type="text" name="title[]" id="name_" required />
I should add that this input element is being added dynamically by javascript, meaning, it's appended after a certain action has taken place.
The true problem is that the code inside of the if statement is never true even when I don't type a value for the given text field.
Any help is appreciated.
The value attribute of an input tag is not the same thing as the value property of an input element. The first one happens to be in the HTML, gets parsed in the DOM and acts as the defaultValue. The latter one is the dynamic value which represents the currently entered input. See also .prop() vs .attr()
Your element does not even have a value attribute, so it will never match the selector. Instead, you will need to use a filter function that checks the properties:
inputs.filter(function() {
return this.required && this.value=="";
// equivalent: $(this).prop("required")
// and $(this).prop("value") or $(this).val()
})
If you mean to select required inputs that are empty, your selector is wrong. The space represents ancestor relationship, parent/children:
if (inputs.filter('[required][value=""]').length) { // Element is `required` and empty
....
}
There are 2 issues with your code.
('[required] [value=""]')
Supposed to be
('[required][value=""]')
And with the above selector you can never select the input below
<input type="text" name="title[]" id="name_" />
as it has no value attribute in the first place. Also required attribute is missing
The inputs that would match your selector would be of this signature
<input type="text" required="true" value="" name="title[]" id="name_" />
Check Fiddle

Inner HTML with input values

have a brief question regarding innerHTML and input values that have been entered. See the brief example below (using jQuery for convenience):
http://jsfiddle.net/F7urT/2/
jQuery:
jQuery(document).ready(function($) {
$('.send').click(function() {
alert( $('.content').html() );
return false;
});
});​
html:
<div class="content">
<input type="text" name="input" value="Old Value" />
<input type="button" class="send" value="Send" />
</div>​
If you edit the input value, then click the 'Send' button, the alert shows that the innerHTML gotten contains the input with the "Old Value", rather than the value the user has entered. Why is this? And how can we get the HTML as a string with user entered input values?
The new value is stored as a property not an attribute, the value can be obtained by inputelement.value, modifying the value does not affect the attribute. If you want the html with the new value just set the attribute to the new value.
For check boxes and radio buttons set the checked attribute, set the innerHTML for text areas, for selects set the selected attribute on the option
http://jsfiddle.net/mowglisanu/F7urT/5/
this solution is better. works for more inputs.
$('input[type=text]').attr('value', function (i, val) { return val; });
$('input[type=checkbox],input[type=radio]').attr('checked', function () { return this.checked; });
$('textarea').html(function () { return this.value; });
$('select').find(':selected').attr('selected', 'selected');
You can't get it with .innerHTML (.html()). Writing into an element doesn't modify the html markup, nor will it change the value attribute in actual markup.
You can only access the current content by directly asking the element for its .value - value. Using jQuery, you can do that via .val() too.
$('#input_id').attr('value',$('#input_id').val()); will put the value into the html
DanCZ & Musa solutions works pretty good, but I had trouble with the textarea.
I have to implement this in a Typescript project and the only way I've found to make the textarea show the value is this :
textarea.innerHTML = textarea.value;

Categories

Resources