How to change the input value when entering the new value - javascript

I have an input with placeholder="YYYY/MM", when the user click the input to enter the data, I want the year and month to dissappear, so only "/" stays.
I already try with my code, however it doesn't work, please help/
var birthdayId = "document.querySelector("#BIRTHDAY")";
if(birthdayId.maxlength < 4){
birthdayId.value = "/";
}
<input type="text" id="BIRTHDAY" name="BIRTHDAY" placeholder="YYYY/MM" maxlength="7" value="YYYY/MM">

Run your code in a focus event listener.
You should be checking the length of the value, not the maxlength property, which never changes.
You shouldn't put the call to document.querySelector in quotes.
Don't set the default value of the input to YYYY/MM, since that will prevent the length test from working. The placeholder is used to display the desired format, you don't need to do it with value as well.
var birthdayId = document.querySelector("#BIRTHDAY");
birthdayId.addEventListener("focus", function() {
if (birthdayId.value.length < 4) {
birthdayId.value = "/";
}
});
<input type="text" id="BIRTHDAY" name="BIRTHDAY" placeholder="YYYY/MM" maxlength="7" value="">

Related

It seems onChange="myFunction()" is only calling my function once?

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Javascript validation using same class every where [duplicate]

This question already has answers here:
Show/hide element without inline Javascript
(2 answers)
Closed 3 years ago.
I have same input class,type in several pages like the following :
<input type="text" name="studentID" id="studentID" class="form-control student-id"/>
what I want using the same class name student-id ,
it will validate student id using the following js :
function validateStudentId(){
var studentId= document.getElementsByClassName('student-id');
if (studentId.length > 0) {
var id = studentId[0].value;
console.log('lengthe'+id.length);
if(id.length > 7){
alert('Please enter valid student id .');
$('.student-id').val("");
return;
}
if(isNaN(id)){
alert('Entered input is not a number .');
$('.student-id').val("");
return;
}
}
}
To do this job I've already done the following :
<input type="text" class="form-control student-id" onchange="validateStudentId()" name="studentid" size="10" maxlength="7" />
An onchange function added. Is there any better way to do this.
coz I have to do this onchange function call every time.
So what I want is to give only class name and it will automatically validate the field using the class name.
Suggest me any better idea, Just dont want to write onchange function every time ??
Thanks
You can use document.querySelectorAll('input.student-id') to select all inputs with that class and then .forEach() on the node list to iterate over them and call the validation function on each of them.
I also replaced the jQuery calls with plain JavaScript because it's really simple for this use case. I switched the check for a numeric value to come before the length check as well, because that seems more logical to me.
function validateStudentId(inputEl) {
var studentId = inputEl;
var id = studentId.value;
console.log('length: ' + id.length);
if (isNaN(id)) {
alert('Entered input is not a number .');
inputEl.value = "";
return;
}
if (id.length > 7) {
alert('Please enter valid student id .');
inputEl.value = "";
return;
}
}
document.querySelectorAll('input.student-id').forEach(function(inputEl) {
inputEl.addEventListener('change', function() {
validateStudentId(this);
});
});
<input type="text" name="studentID" id="studentID" class="form-control student-id" value="abc" />
<input type="text" name="studentID2" id="studentID2" class="form-control student-id" value="1234567890" />
<input type="text" name="studentID3" id="studentID3" class="form-control student-id" value="123456" />

display a hidden input field when enter value on a particuloar input filed

anyone could help me out on how i could achieve this with either javascript or jquery maybe to get the following as mentioned below
say i have this field1
<input type="text" name="field1" value="">
and then i have this field2
<input type="hidden" name="field2" value="">
what i mean to say the field2 should be hidden but if someone enters some value in field1 then field2 shows but if no value on field1 then it disappears?
thanks in advance and appreciate your time and help
You'd get the first field, check if it has a value, and toggle the second field based on that, but you should not be using a hidden input, but instead hide it with CSS
$('[name="field1"]').on('input', function() {
var el = $('[name="field2"]').toggle( this.value !== "" );
if (this.value === "") el.val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="field1" value="" placeholder="type something">
<br><br>
<input type="text" name="field2" value="" style="display:none">
As you've also tagged your question with JavaScript it seems worth offering the following:
// retrieving the first - if any - element with its
// 'name' attribute equal to the value of 'field1':
var input = document.querySelector('[name=field1]');
// adding an event-listener to that element, listening
// for the 'input' event (keyup, paste, copy...) and
// assigning the method's anonymous function as the
// event-handler:
input.addEventListener('input', function(e) {
// 'e': here unused, is a reference to the event
// which triggered the function to be called; using
// e.type will give the specific event, if required
// (and other properties are, of course, available).
// retrieving the first - if any - element with has
// its 'name' attribute equal to 'field2':
var conditionalInput = document.querySelector('[name=field2]');
// if the value of the <input> element that received
// the event has a value that, when leading and trailing
// white-space is removed, results in a truthy
// evaluation (the string length is non-zero):
if (this.value.trim().length) {
// we set the display style of the conditionally-
// shown <input> to 'block', you could instead use
// 'inline-block' if you prefer:
conditionalInput.style.display = 'block';
// otherwise, if the length of the trimmed-value is
// zero (falsey):
} else {
// we set the display style of the conditionally-
// shown <input> to 'none':
conditionalInput.style.display = 'none';
// and also remove its entered value:
conditionalInput.value = '';
}
});
var input = document.querySelector('[name=field1]');
input.addEventListener('input', function(e) {
var conditionalInput = document.querySelector('[name=field2]');
if (this.value.trim().length) {
conditionalInput.style.display = 'block';
} else {
conditionalInput.style.display = 'none';
conditionalInput.value = '';
}
});
<input type="text" name="field1" value="" />
<input type="text" name="field2" value="" />
In your HTML please note that I've adjusted the <input> element's type, from 'hidden' to 'text', this is because some browsers – I believe mostly Internet Explorer – has, or had, issues when changing the type of an <input> element dynamically.
If your use-case doesn't depend on cross-browser compatibility then you can, of course, change the type (conditionalInput.type = 'text'/conditionalInput.type = 'hidden') rather than the display.

How to have unique suggestion on input in SAPUI5

I am trying to get suggestions from input box, but if model has multiple values in wheelName like "wheel1", "wheel1", "wheel2", and with this, when I enter "wheel1" in inputbox, i get 2 suggestions as wheel1, wheel1, but i want unique suggestion i.e. wheel1 to be shown only once.
Input declaration looks like below:-
<Input
id="wheelInput"
type="Text"
placeholder="Enter Wheel..."
showSuggestion="true"
maxLength="40"
startSuggestion="3"
suggestionItems="{wheel>/results}" >
<suggestionItems>
<core:Item text="{wheel>wheelName}"/>
</suggestionItems>
</Input>
Assuming your results list differs with every character you type into your input, you can attach a function to the liveChange of the Input field.
You can then put your custom logic (e.g. no double names) into a separate model property. I haven't tested the code but Ii should work (provided I didn't make a typo).
View:
<Input
id="wheelInput"
type="Text"
placeholder="Enter Wheel..."
showSuggestion="true"
maxLength="40"
liveChange="filterWheelList"
startSuggestion="3"
suggestionItems="{wheel>/filteredWheelList}" >
<suggestionItems>
<core:Item text="{wheel>wheelName}"/>
</suggestionItems>
</Input>
Controller:
filterWheelList: function(){
var wheelModel = sap.ui.getCore().getModel("wheelModel");
var wheelList = wheelModel.getProperty("/results");
var uniqueNames = [];
var filteredWheelList = wheelList.filter(function(wheel){
if (uniqueNames.indexOf(wheel.wheelName) === -1){
uniqueNames.push(wheel.wheelName);
return true;
} else {
return false;
}
});
wheelModel.setProperty("/filteredWheelList", filteredWheelList);
}

select function focus function and text field value is not working

<input type="text" name="last" size="16 ONCHANGE ="nameselect();">
function nameselect(){
if(isBlank(""+document.contest.last.value)){
document.contest.last.value = "surname"
document.contest.last.focus();
document.contest.last.select();
}
}
function isBlank(s){
var len = s.length;
for(var i =0; i<len;++i){
if(s.charAt(i)!="") return false;
}
return true;
}
Last name: <input type="text" name="last" size="16 ONCHANGE ="nameselect();">
i am having text field on which onchange function is running. in this function if the text field is empty then automatically it has to set as surname and the current focus set to the field and text got selected as well but none of the applies function is working, its quite confusing for me.
The HTML is probably causing you some issues.
See that the attribute is not closed properly size="16 ONCHANGE ="
In your example you have
<input type="text" name="last" size="16 ONCHANGE ="nameselect();">
it should be:
<input type="text" name="last" size="16" onChange="nameselect();">
That should be the start at least.

Categories