Getting a variable from the input and displaying it again - javascript

helo guys I am writing ajava Script that have an input box to allow the user enter a value and I want to show him again what he enterd with in that page to ensure that he will see what he is enterd for example
<input id="userName" class="form-control col-md-7 col-xs-12" type="text" name="userName">
I have these input box and I want get this value and display it again in alabel bellow
<label id="user_label" class="control-label col-md-3 col-sm-3 col-xs-12"></label>
and I write the following JS
user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name;
and these displays the string userName not the string value init what can I do

Just grab the value from the HTML element instead...
var user_Name = document.getElementById('userName').value;
document.getElementById('user_label').innerHTML = user_Name;

What you need to do is call your code whenever the input field is changed.
<input id="userName" type="text" name="userName" onKeyUp="update()">
And in JS:
function update() {
var user_Name=document.getElementById('userName').value;
document.getElementById('user_label').innerHTML=user_Name;
}
Also you need to refer to the .value of the input element to get its value.
Here is a Pen:
http://codepen.io/calvinclaus/pen/EKBvBz?editors=1011

Try:
var user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name.value;

Related

Form Validation Not Resetting After Failing Validation

I'm using a small script to validate a postcode, which works and stops the user entering an invalid password, but when an invalid post code is entered you then can't submit a correct entry. For example, if I enter 'ST' I get the message telling me the postcode is invalid, so without refreshing the page manually I enter 'ST6 1SA' (which is a valid Stoke postcode) and I can't submit the form, I just keep getting the invalid tool tip advising me the post code is not in the correct format.
JS:
<script>
// Validate the postcode before it's sent
(function () {
var postcode = document.getElementById('postcode-entry');
var wrapper = document.getElementById('validation');
var notify = document.createElement('div');
var mnisLookup = document.getElementById('mnis-results');
var matchingClients = document.getElementById('matching-clients');
var postcodeWrapper = document.getElementById('postcode-wrapper');
notify.id = 'notify';
notify.style.display = 'none';
wrapper.appendChild(notify);
postcode.addEventListener('invalid', function (event) {
if (!event.target.validity.valid) {
notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
notify.className = 'error';
notify.style.display = 'block';
postcode.className = 'form-control invalid';
}
});
})();
</script>
HTML:
<form id="postcode-wrapper" class="form-horizontal">
<div id="postcode-lookup" class="form-group">
<label for="postcode-entry" class="col-sm-1">Postcode:</label>
<div id="postcode-entry-wrapper" class="col-sm-3">
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
</div>
<div class="col-sm-1">
<input id="search" type="submit" value="Search" class="btn btn-default" />
</div>
<div id="validation" class="col-sm-7"></div>
</div>
</form>
Just a quick note that may affect how the page is refreshing, this is inside an MVC Razor page and wrapped with Html.BeginForm - not sure if that makes a difference?
While debugging your code, i found that the event.target.validity.valid was returning false even if the input was valid e.g. 'ST6 1SA'. This was occuring because it does not update the custom validation for the new input and the previous state persists even after entering the valid input.
So to update and reset the previous validation, you have to reset setCustomValidity('') on input change, i.e. oninput="setCustomValidity('')"
Please replace this code:
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" oninput="setCustomValidity('')"/>

Full Name From User To be In Separated Hidden Form Fields

I have a form with the two below inputs
<div class="required form-group" style="display:none">
<label for="customer_firstname">{l s='First name'}
<sup>*</sup>
</label>
<input onkeyup="$('#firstname').val(this.value);" type="text" class="is_required validate form-control" data-validate="isName" id="customer_firstname" name="customer_firstname" value="{if isset($smarty.post.customer_firstname)}{$smarty.post.customer_firstname}{/if}" />
</div>
<div class="required form-group" style="display:none">
<label for="customer_lastname">{l s='Last name'}
<sup>*</sup>
</label>
<input onkeyup="$('#lastname').val(this.value);" type="text" class="is_required validate form-control" data-validate="isName" id="customer_lastname" name="customer_lastname" value="{if isset($smarty.post.customer_lastname)}{$smarty.post.customer_lastname}{/if}" />
</div>
As you can see both these fields are hidden. This is because I want to create a new input called full name and whatever the user types here gets filled into these first name and last name automatically.
So if full name is John Doe then first name will hold John and last name will hold Doe. Or if full name is Stuart Ben Mackenzie then fist name will hold Stuart Ben and last name will hold Mackenzie. How can I do this with Javascript??
You should use this:
<input id="fullname" type="text"/>
$('#fullname').val($('#firstname').val()+' '+$('#lastname').val());
This really depends on how you want to discern the first name from the last. If you want the last name to always be only 1 word then it you would parse the names as such.
Add to your input(s) which you need to track input a class or attribute then simply bind the keyup event handler to it such as
$("input[traced-input]").on("keyup", function(){
var tft = $(this); //short for thisTextField
if(tft.attr("id")==='fullname'){
//parse the names here into an array presumably
$("#firstname").val(namesArr['firstname']);
$("lastname").val(namesArr['lastname']);
}
});
Make sure you put the js in $(document).ready() and if the HTML content will be dynamically loaded then add a delegate such as
$(document).on("keyup", '.class or #id here', function () {
//do stuff
});
You can achive using bellow code:
<input id="fullname" type="text"/>
var fullname=$('#fullname').val();
var pieces = fullname.split(' ');
var customer_lastname=pieces[pieces.length-1];
$("#customer_lastname").val(customer_lastname);
pieces.pop();
var customer_firstname=pieces.join(" ");
$("#customer_firstname").val(customer_firstname);
$('#dfullname').on('keyup', function(e){
var fullname = $(this).val();
var splitFullName = fullname.split(' ');
$('#firstname').val(splitFullName[0]);
$('lastname').val(splitFullName[1]);
});
of course this will only work if you are having 1 first name and 1 last name, but it gives you the general idea.

Keep input value after refresh page

I have a form with input field and this input contain a drop down menu read information from database.
If the user enters value and when he arrives to the drop menu he doesn't find what he wants he go to another page to add this info to the drop down menu and then go to the first page to continue enter the information.
How can I keep this information if he goes to another page to add info to drop menu and how can after adding the info to drop menu find this info without refresh and without submit.
This is the first page with the form
<form name='' method='post' action='<?php $_PHP_SELF ?>'>
<input name='txt_name' id='' type='text'>
This drop menu read from database
<select id="groups" name="txt_label" class="form-control">
';?>
<?php
$sql=mysqli_query($conn,"select DISTINCT db_label from tbl_label")or die(mysqli_error($conn));
echo'<option value="">-- Select --</option>';
while($row=mysqli_fetch_array($sql)){
$label=$row['db_label'];
echo "<option value='$label'>$label</option>";
}echo'</select>';?><?php echo'
</div>
</form>
Second form in another page
<form class="form-inline" role="form" name="form" method="post" action="';?><?php $_PHP_SELF ?><?php echo'">
<div class="form-group">
<label for="pwd">Label</label>
<input id="txt_label" name="txt_label" type="text" placeholder="Label" class="form-control input-md">
</div>
<div class="form-group">
<label for="pwd">Sub Label</label>
<input id="txt_sublabel" name="txt_sublabel" type="text" placeholder="SubLabel" class="form-control input-md">
</div>
<input type="submit" name="addlabel" value="Add" class="btn btn-default">';
EDIT: Keep value of more inputs
HTML:
<input type="text" id="txt_1" onkeyup='saveValue(this);'/>
<input type="text" id="txt_2" onkeyup='saveValue(this);'/>
Javascript:
<script type="text/javascript">
document.getElementById("txt_1").value = getSavedValue("txt_1"); // set the value to this input
document.getElementById("txt_2").value = getSavedValue("txt_2"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
if the above code did not work try this:
<input type="text" id="txt_1" onchange='saveValue(this);'/>
<input type="text" id="txt_2" onchange='saveValue(this);'/>
You can also use useContext() from react context() if you're using hooks.
In MVC/Razor,
first you should add a variable in your model class for
the textBox like this:
namespace MVCStepByStep.Models
{
public class CustomerClass
{
public string CustomerName { get; set; }
}
}
Then in Views --> Index.cshtml file make sure the Textbox
is created like this:
#Html.TextBoxFor(m => m.CustomerName)
For a complete example, please check out this site:
How to update a C# MVC TextBox By Clicking a Button using JQuery – C# MVC Step By STep[^]

Using HTML form field validation

I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.

How to disable validation while opening dialog box on edit mode?

when trying to open dialog in edit mode, validation message pop up with required message. but what i need to achieve is that when opening dialog box on edit mode as text box will contain value as soon as dialog box opens but then also validation message is there. how to remove that if already a value present in text box.
Example below for HTML code how I am using it.
<div class="form-group col-lg-6" show-errors>
<label for="firstName">First Name</label>
<input type="text" class="form-control" id="firstName" ng-model="firstName" name="firstName" placeholder="First Name" style="width: 74%;" required>
<p class="help-block" ng-if="EditUserUserform.firstName.$error.required">Required</p>
</div>
<div class="form-group col-lg-6" show-errors>
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" ng-model="lastName" name="lastName" placeholder="Last Name" style="width: 74%;" required>
<p class="help-block" ng-if="EditUserUserform.lastName.$error.required">Required</p>
</div>
app.directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box so we know the property to check
// on the form controller
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
}
}
});
Below is the image when i am opening form in normal mode.
And below image shows when i open in edit mode.
the value already present in it but as soon as dialog opens it show validation message.
I don't know angular at all and this is assuming you have access to the context of whether this is in edit mode or not, but it looks like you could do something here:
inputNgEl.bind('blur', function() {
//only check if not edit mode
if (!edit) {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
}
});
unless angular has its own hooks to achieve the same thing, I'd say you could do it doing something like that.
Normally, if an input field hasn't been touched, the field's value didn't be filled by a user but by using controller , the $pristine will be true. So, you could fix this by firstly verifying the $pristine value:
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
// Only do this if and only if the field has been touched and the value is invalid
el.toggleClass('has-error', !formCtrl[inputName].$pristine && formCtrl[inputName].$invalid);
});
Alternatively, you could use $dirty value which will be false if the field hasn't been touched.
el.toggleClass('has-error', formCtrl[inputName].$dirty && formCtrl[inputName].$invalid);

Categories