If I enter something into t1, t2 is changed.
But if t2 already has manual input, it is not changed any more (and vice versa).
How can I change an input field that has already an manual input with javascript (without reloading the page!)?
<!DOCTYPE html>
<html>
<body>
inputfields are not changed, if they have/had an input already!<br />
<br />
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
<script>
function upd1() {
t2.setAttribute("value", "changed");
return true;
}
function upd2() {
t1.setAttribute("value", "changed");
return true;
}
</script>
</body>
</html>
You can also save an old value of each field to continue editing. Also it will show editing status on another field each time. It will be more comfortable for users.
inputfields are not changed, if they have/had an input already!<br />
<br />
<input type="text" id="t1" value="" onClick="renderFirstEl()" onInput="upd1()"><br /><br />
<input type="text" id="t2" value="" onClick="renderSecondEl()" onInput="upd2()">
<script>
let firstElValue = '';
let secondElValue = '';
function upd1() {
let el = document.querySelector('#t2');
el.value = 'changed';
return true;
}
function upd2() {
let el = document.querySelector('#t1');
el.value = 'changed';
return true;
}
function renderFirstEl() {
let el = document.querySelector('#t1');
secondElValue = document.querySelector('#t2').value;
el.value = firstElValue;
}
function renderSecondEl() {
let el = document.querySelector('#t2');
firstElValue = document.querySelector('#t1').value;
el.value = secondElValue;
}
</script>
The simple answer is use this:
function upd1() {
t2.value = 'changed';
return true;
}
function upd2() {
t1.value = 'changed';
return true;
}
t1: <input type="text" id="t1" value="" onchange="upd1()"><br /><br />
t2: <input type="text" id="t2" value="" onchange="upd2()">
Value changes after you type in one of the inputs and press Enter.
Because as said here: https://www.w3schools.com/jsref/met_element_setattribute.asp .
"The setAttribute() method adds the specified attribute to an element, and gives it the specified value.
If the specified attribute already exists, only the value is set/changed."
Related
I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful
I have two fields where the second field has a value and whatever value is entered in the first field is added to the second value.
Now when it is added and the number entered in the first field is deleted(erased with backspace) the value of the second field does not not return to it's original value. How do I go about this? Also I won't mind a better way to approach onkeyup in this situation
Html:
First: <input type="text" id="vala" onkeyup="sum();" />
Second: <input type="text" id="valb" value="12" />
JS:
function sum() {
var first = document.getElementById('vala').value;
var second = document.getElementById('valb').value;
var result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
document.getElementById('valb').value = result;
}
}
Working fiddle representation:
http://jsfiddle.net/wcvqby2g/
I think you're looking for
function sum() {
var first = document.getElementById('vala').value;
var second = document.getElementById('valb').defaultValue;
var result = (parseInt(first) || 0) + parseInt(second);
document.getElementById('valb').value = result;
}
where the defaultValue property of the input accesses the original value of the input, i.e. the one specified in the value attribute.
(updated fiddle)
It was overwritten.
You can store original value like this:
First: <input type="text" id="vala" onkeyup="sum();" />
Second: <input type="text" id="valb" value="12" data-default-value="12" />
...and add this to your JS:
else {
document.getElementById('valb').value = document.getElementById('valb').dataset.defaultValue;
}
Here's a fiddle: http://jsfiddle.net/andunai/wcvqby2g/5/
Notice that data-default-value becomes dataset.defaultValue
this is working solution--
First: <input type="text" id="vala" onkeyup="sum();" />
Second: <input type="text" id="valb" value="12" />
<script>
var second1=document.getElementById('valb').value;
var first1=document.getElementById('vala').value;
function sum() {
var first = document.getElementById('vala').value;
var second = document.getElementById('valb').value;
var result = parseInt(first) + parseInt(second1);
if (!isNaN(result)) {
document.getElementById('valb').value = result;
}
if(first == first1)
{
document.getElementById('valb').value= second1;
}
}
</script>
I am attempting to check the field to determine whether or not it is a number (no non-numeric characters except .). If the field's value is a number, convert it to a two-decimal format. Currently the code is working in FireFox and Chrome, but I am having trouble with Internet Explorer (multiple versions, specifically tested on IE8 and IE9). I have been messing around with it for a few hours and haven't been able to look up a solution to the problem. In Internet Explorer, only the first field works correctly. The other fields do not work correctly and Internet Explorer does not trigger an error.
This is the relevant code in the html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" src="amount.js"></script>
</head>
<body>
<input type="text" id="amount1" onChange="changeAmount(this.id);"/>
<input type="text" id="amount2" onChange="changeAmount(this.id);"/>
<input type="text" id="amount3" onChange="changeAmount(this.id);"/>
<input type="text" id="amount4" onChange="changeAmount(this.id);"/>
<input type="text" id="amount5" onChange="changeAmount(this.id);"/>
</body>
</html>
This is the relevant code from amount.js:
function changeAmount(input)
{
var pattern = /([^0-9\.])+/;
var ctl = document.getElementById(input);
var myvalue = ctl.value;
if(myvalue != "" && !pattern.test(myvalue))
{
myvalue = parseFloat(myvalue);
myvalue = myvalue.toFixed(2);
if(!pattern.test(myvalue))
{
ctl.value = myvalue;
}else
{
ctl.value = '';
}
}
}
I am going to browse some more threads on here to see if I can't find the solution.
Thanks for any help in advance.
With this HTML:
<input type="text" id="amount1" onChange="changeAmount(this);"/>
<input type="text" id="amount2" onChange="changeAmount(this);"/>
<input type="text" id="amount3" onChange="changeAmount(this);"/>
<input type="text" id="amount4" onChange="changeAmount(this);"/>
<input type="text" id="amount5" onChange="changeAmount(this);"/>
Try using this Javascript:
function changeAmount(input) {
var myvalue = input.value;
myvalue = parseFloat(myvalue);
if (!isNaN(myvalue)) {
input.value = myvalue.toFixed(2);
} else {
input.value = "";
}
}
DEMO: http://jsfiddle.net/7rDeg/4/
It uses my recommended change of passing this instead of this.value to the function.
Also, there's no need for regular expressions. Just attempt to parse the value with parseFloat. If it's a success, then fix the number with 2 decimals and re-set the input's value. Otherwise, clear the textbox.
UPDATE:
While that should all work fine, I'd recommend against using inline event handlers. So for example, it's ideal to use this HTML:
<input type="text" id="amount1" />
<input type="text" id="amount2" />
<input type="text" id="amount3" />
<input type="text" id="amount4" />
<input type="text" id="amount5" />
with this Javascript:
function changeAmount() {
var myvalue = this.value;
myvalue = parseFloat(myvalue);
if (!isNaN(myvalue)) {
this.value = myvalue.toFixed(2);
} else {
this.value = "";
}
}
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
window.onload = function () {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "text") {
addEvent(inputs[i], "change", changeAmount);
}
}
};
DEMO: http://jsfiddle.net/7rDeg/6/
Note: With parseFloat, it will strip any trailing non-numeric characters. For example, the input "234.35234a" will be parsed as "234.35234" (therefore passing the !isNaN(myvalue) condition) and fixed as "234.35". If you don't want this to happen use:
myvalue = +myvalue;
instead of the parseFloat line.
i have code it can be sum two textbox values using javascript but problem is that when i entered amount into recamt textbox value and javascript count again and again recamt textbox values it should be count only one time recamt textbox value not again and again?
<script type="text/javascript">
function B(){
document.getElementById('advance').value
=(parseFloat(document.getElementById('advance').value))+
(parseFloat(document.getElementById('recamt').value));
return false;
}
</script>
<input class="input_field2" type="text" readonly name="advance"
id="advance" value="50" onfocus="return B(0);" /><br />
<input class="input_field2" type="text" name="recamt" id="recamt">
You could keep a property on the read-only text field to keep the old value:
function B()
{
var adv = document.getElementById('advance'),
rec = document.getElementById('recamt');
if (typeof adv.oldvalue === 'undefined') {
adv.oldvalue = parseFloat(adv.value); // keep old value
}
adv.value = adv.oldvalue + parseFloat(rec.value));
rec.value = '';
return false;
}
You're calling the sum function every time the readonly input is focused using the new value. If you only want it to add to the original value, you need to store it somewhere.
HTML:
<input type="text" id="advance" readonly="readonly" value="50" /><br />
<input type="text" id="recamt">
JS:
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onclick = function() {
this.value = parseFloat(originalValue) +
parseFloat(document.getElementById('recamt').value);
return false;
};
http://jsfiddle.net/hQbhq/
Notes:
You should bind your handlers in javascript, not HTML.
The javascript would need to exist after the HTML on the page, or inside of a window.load handler, otherwise it will not be able to find advanceBox.
I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
And here is the form.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!
You can get a collection of all these textboxes with document.getElementsByName. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
DEMO
Function is iterating by all of the student text boxes and return true if some element is filled out. Protected against that if input contain only spaces :)
function submitIt() {
for( var i = 0, t = document.getElementsByName( "Student_ID" ), l = t.length; i < l; i++ )
if( t[i].value && !/^\s+$/.test( t[i].value ) )
return true;
return false
}
Demo on: http://jsfiddle.net/hhD2x/
you can use jquery.
add common class name for all your textboxes i.e.
<input name="Student_ID" type="text" id="idField1" class="student" />
now in js function
function submit()
{
$('.student').each(function() {
if($(this).val() == '' || $(this).val() == null)
{
// your error message
return false;
}
}
}
this function check all the elements with student class.
$('input[type="text"], select,
:input[type="date"],
:input[type="email"],
:input[type="radio"]').each(function () {
if ($.trim($(this).val()) == '' ) {
// your error message here
isValid = false;
}
});