Set Value of Input Using Javascript Function - javascript

I'm currently using a YUI gadget. I also do have a Javascript function to validate the output that comes from the div that YUI draws for me:
Event.on("addGadgetUrl", "click", function(){
var url = Dom.get("gadget_url").value; /* line x ------>*/
if (url == "") {
error.innerHTML = "<p> error" /></p>";
} else {
/* line y ---> */
/* I need to add some code in here to set the value of "gadget_url" by "" */
}
}, null, true);
Here is my div:
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input"/>
<input type="button" id="addGadgetUrl" value="add gadget"/>
<br>
<span id="error"></span>
</div>
As you can see my question is, how can I set the value of gadget_url to be ""?

Javascript
document.getElementById('gadget_url').value = '';
jQuery
$("#gadget_url").val("");
YUI
Dom.get("gadget_url").set("value","");

document.getElementById('gadget_url').value = '';

The following works in MVC5:
document.getElementById('theID').value = 'new value';

Depending on the usecase it makes a difference whether you use javascript (element.value = x) or jQuery $(element).val(x);
When x is undefined jQuery results in an empty String whereas javascript results in "undefined" as a String.

document.getElementById('gadget_url').value = 'your value';

I'm not using YUI, but my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).
Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.

Shortest
gadget_url.value=''
addGadgetUrl.addEventListener('click', () => {
gadget_url.value = '';
});
<div>
<p>URL</p>
<input type="text" name="gadget_url" id="gadget_url" style="width: 350px;" class="input" value="some value" />
<input type="button" id="addGadgetUrl" value="add gadget" />
<br>
<span id="error"></span>
</div>
This is the shortest working solution (JSFiddle).

Related

how to make html input required using JavaScript?

Could you tell me how to achieve html input:
<input id="blablabla" required> using javascript
all web answers i have found suggest to write something like:
input.setAttribute('required','true');
input.setAttribute('required','');
input.required='true'
but them all give me something like:
<input id="blablabla" required=''>
or
<input id="blablabla" required='true >
and they doesn't work
Only html that works is <input id="blablabla" required>
Could you help me ?
Thanks
I found your example as well as the other answers working perfectly.
Are you sure you did the right thing?
Also you can put like this, it will work too!
myInput.setAttribute('required', 'required');
Example code:
Please click Add required and then click Submit
function addRequired() {
const myInput = document.getElementById('inputText');
myInput.setAttribute('required', 'required');
alert('Input has been added required!');
}
function removeRequired() {
const myInput = document.getElementById('inputText');
myInput.removeAttribute('required');
alert('Input has been removed required!');
}
<form>
<input id="inputText" type="text">
<button type="button" onclick="addRequired()">Add required</button>
<button type="button" onclick="removeRequired()">Remove required</button>
<button>Submit</button>
</form>
You can do this in any of the following ways:
const myInput = document.getElementById('blablabla');
myInput.required = true // Method 1
myInput.setAttribute('required', true); // Method 2
To get something like <input id="blablabla" required> you have to use the first method
If you're looking for the typical asterisk to appear, that's something you have to add manually, with JS or CSS. But if you check the attributes of the element (by inspecting the HTML of the page) you can see that the required attribute has been added.

jQuery parseInt() results in NaN

Problem Summary
I have been working on adding up various numbers in fields, based on the value of input boxes. I am currently experiencing the issue in which jQuery is concatenating the value arguments as they are strings and I have been unable to successfully convert them to integers.
Further Description
Here is an example of the HTML I am using:
<form action="" method="post">
<input type="text" id="one" value="20.00" />
<input type="text" id="two" value="10.00" />
<a href="#" id="add">
Add up fields
</a>
<input type="submit" value="Submit" />
</form>
Here is my jQuery (this behavior described above was to be expected with this script):
$(function(){
var one = $('#one').val(),
two = $('#two').val();
$('#add').click(function(e){
e.preventDefault;
var three = one + two;
alert(three);
});
});
This resulted obviously in the output:
20.0010.00
So I tried modifying my first variable declarions with parseInt() like so:
var one = parseInt($('#one').val(),10),
two = parseInt($('#two').val(),10);
Nowever that just resulted in:
NaN
so I tried first obtaining the values and then converting to integers:
var one = $('#one').val(),
two = $('#two').val(),
i_one = parseInt(one),
i_two = parseInt(two);
But yet agan... NaN was the result of this.
I have also tried the above using parseFloat() which yielded the same unfortunate results.
I also tried (read somewhere on a blog) that adding + in front will force jQuery to treat the variables as integers so I did (see above for where i got one and two):
u_one = +one
u_two = +two
I am starting to think that obtaining values using val() prevents jQuery utilising them as anything other than strings... But I must be wrong.
Can you advise on how I can obtain these values in integer format so that I can have the result:
30.00
When the fields are added?
Preferebly whilst keeping the <input /> and not adding another hidden <span /> or something similar containing the number to which then I can run text() on.
Thanks for reading.
NOTE
It has come to light the problem was not related to jQuery and related to the template I was making use of. Code above works as pointed out in the comments below. I have accepted one as an answer however all jQuery examples posted will work.
try this way
$(function(){
var one = $('#one').val();
var two = $('#two').val();
$('#add').click(function(e){
e.preventDefault;
var three = parseInt(one) + parseInt(two);
alert(three);
});
});
refer working demo on jsfiddle :http://jsfiddle.net/adeshpandey/Y3xmW/
Use : var three = parseFloat(one + two);
See Demo
You are completely looking at the wrong problem!
You are extracting the value before the click occurs; the value is empty-string at that point.
the other way
$(function(){
var one = $('#one').val();
var two = $('#two').val();
$('#add').click(function(e){
e.preventDefault;
var three = parseInt(one) + parseInt(two);
$('#three').text("Total: " +three);
});
});
HTML
<form action="" method="post">
<input type="text" id="one" value="20.00" />
<input type="text" id="two" value="10.00" />
<a href="#" id="add">
Add up fields
</a>
<p id="three"></p>
<input type="submit" value="Submit" />
</form>
Try changing your input tags to type number:
<input type="number" id="one" value="20.00" />

AJAX function not being called with button onclick function

I have a simple form with 2 input fields and one button. When the button is clicked, the value of the 2 input fields should be sent to the AJAX function to be handled in a servlet. For some reason, the servlet is not being reached. Can anyone see why? I have an almost identical method working with a different form, and I can't see why this one isn't working.
Here is the HTML form code:
<div id="addCourses" class="hidden" align="center" >
<form id="addCourse" name="addCourse">
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" value="Add Course" onclick="addCourse(this.courseID.value, this.courseDesc.value);"/>
</form>
</div>
Here is the Script function:
<script type ="text/javascript">
function addCourse(id, descr)
{
var fluffy;
fluffy=new XMLHttpRequest();
fluffy.onreadystatechange=function()
{
if (fluffy.readyState==4 && fluffy.status==200)
{
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
}
</script>
Because this is the button and not the form
so
this.courseID.value
this.courseDesc.value
returns an error.
You should use
this.form.courseID.value
this.form.courseDesc.value
Second problem is you have a name clash. The form and function are named addCourse. It will lead to problems. Rename one of them to be different.
Running Example
When you use this, as in onclick="addCourse(this.courseID.value, this.courseDesc.value);", I think that would refer to the input element, and therefore the values aren't being passed correctly.
Bind your event handlers in javascript, where they should be, and you can avoid the issue entirely.
HTML:
<input type="text" id="courseID" name="courseID" value="courseID" size="40" /><br />
<textarea rows="5" cols="33" id="courseDesc" name="courseDesc">Description</textarea><br />
<input type="button" id="addCourse" value="Add Course"/>
JS:
document.getElementById('addCourse').onclick = function () {
var fluffy = new XMLHttpRequest();
var id = document.getElementById('courseID').value;
var descr = document.getElementById('courseDesc').value;
fluffy.onreadystatechange=function() {
if (fluffy.readyState==4 && fluffy.status==200) {
//do something here
}
};
fluffy.open("GET","ajaxServlet?courseID="+id+"&courseDescription="+descr,true);
fluffy.send();
};
As epascarello pointed out, you need to change the ID of your form as having two elements with the same ID is not allowed and will cause unpredictable javascript behavior.
Try a fluffy.close; after the if ready state expression.

"uncaught TypeError: Object is not a function" in JavaScript

I am having trouble understanding why this is not working. I have two fields on my form and when I click a button another text field value is changed to that if the function. How can I get this to work?
function calculate()
{
var odometerStart = parseFloat (document.getElementById('odometerStart').value);
var odometerEnd = parseFloat(document.getElementById('odometerEnd').value);
var distance = document.getElementById('distance');
var amount = document.getElementById('amount');
distance.value = odometerEnd - odometerStart;
}
var val = $("#taskentry").validate({
rules: {
tripDate: {required: true}
tripContact: {required: true}
odometerStart: {required: true}
}
});
Odometer: Start <input type="number" name="odometer[Start]" id="odometerStart" min="0" max="999999" placeholder="0" class="required"/><br/>
Odometer: End <input type="number" name="odometer[End]" id="odometerEnd" min="0" max="999999" placeholder="999999" class="required"/><br/>
Comments <textarea name="comments" id="comments" rows="2" cols="2"></textarea><br/>
Distance <input type="text" name="distance" id="distance" value="" placeholder="0.00"/><br/>
<input type="button" name="calculate" value="Calculate" onclick="calculate()"/>
I am debuging this in Google Chrome using the developer tools and am getting the error "uncaught TypeError: Object is not a function" at the point where the calculate button is.
Sorry for the huge gap between your question and my answer :)
I just got the same problem and found the reason - browser automatically populates objects based on ID attributes of the html tags in the page.
Simple test
<div id='test'>Just testing</div>
<script type='text/javascript'>
alert(test.innerHTML);
</script>
In your case you had an element with id='calculate', rename it or rename the function you are using for calculations.
In my case, I have
<input type="button" class="button" id="register" title="register" value="Sign Up!" onclick="register()" />
and get the same warning when I call the javascript function register(), I guess it is conflicted with id or title attributes in the input tag, so I just alter this function into another name such as signup() and it works around.
I hope it helps. :)
I had this problem with a function I created, working perfectly with Firefox and giving this error with Chrome and Safari. The solution: change the name of the function. The original name was expand(target), replaced by expand_compress(target). And it worked. I suppose that the function expand() is existing somewhere else than in Firefox
Perhaps you need commas:
var val = $("#taskentry").validate({
rules: {
tripDate: {required: true},
tripContact: {required: true},
odometerStart: {required: true}
}
});

Increase/decrease textfield value with javascript

I'm having trouble in doing a javascript that will do the following:
Increase/decrease number inside textbox when image clicked.
setting a limit for that textbox (not below zero, not above x)
please know i have many text boxes in the same page, so how can this issue be fixed?
You don't need to (and shouldn't) set ids for each and every image and input field. You will need to set name attributes for each input field though (so your server code can tell them apart - but not for JS).
If the "add" section for each row looks like:
<div>
<img src='minus.png' onclick="increment(this.parentNode.getElementsByTagName('input')[0]);" />
<input type='text' name='product_1010101011' />
<img src='plus.png' onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);" />
</div>
use this javascript:
function increment(myInput) {
// use Mike Samuel's code here
myInput.value = (+myInput.value + 1) || 0;
}
function decrement(myInput) {
// use Mike Samuel's code here
myInput.value = (myInput.value - 1) || 0;
}
I think this should get you going:
<form>
<input type="button" id="minus" value="-"
onClick="textb.value = (textb.value-1)">
<input type="text" id="textb" name="name" value="1" />
<input type="button" value="+"
onClick="textb.value = (+textb.value+1)">
</form>
Live example here
To increment
myInput.value = (+myInput.value + 1) || 0;
To decrement
myInput.value = (myInput.value - 1) || 0;
The || 0 will reset any value that doesn't parse as an integer to a default value, 0.

Categories