How to remove attributes from HTML using javascript? - javascript

I have an HTML with say a textfield (input element).
<input name="capacity" type="text" value="blah blah blah">
This simply displays a text field on my page with a default value "blah blah blah".
What I want to do is remove value attribute, as I don't want to see this default value.
I am doing this using javascript.
value = element.getAttribute("value");
if((element.readOnly != undefined || element.readOnly == false) || (element.disabled != undefined || element.disabled == false)){
//element.removeAttribute(value);
element.removeAttribute("value");
But it is not working. I even tried
element.setAttribute("value","");
but no luck.
Any pointers where I may be missing.
EDIT :
I got an issue related to this question, anyone interested may check this
*********************************************
Thanks a lot.

...I don't want to see this default value.
Just set the value property directly to an empty string.
document.getElementsByName('capacity')[0].value = '';
jsFiddle.

Give your text field and id like <input name="capacity" type="text" id="text" value="blah blah blah"> document.getElementById['text'].value = "";

This is your html tag. You will need to add a ID to it
<input id="capacity" name="capacity" type="text" value="blah blah blah">
This is just to fire the javascript function
<input type="submit" value="Click" onclick="javascript:return reset();" />
The following function will reset the value of the selected element
<script type="text/javascript" language="javascript">
function reset() {
document.getElementById("capacity").value = "";
return false; // In order to avoid postback
}
</script>
If you are not using form and you want to use it with just the name you can try the following
this.capacity.value = '';

Related

How to display current date, day and time inside a read only textbox? [duplicate]

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).

innerHTML to input value [duplicate]

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).

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.
I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect".
How i can do it, help.
<form action="" method="post">
<input type="text" name="text1" placeholder="Text 1">
</br>
<input type="text" name="text2" placeholder="Text 2">
</br>
<input type="submit" value="Enter">
</form>
What kind of validation are you interested in ?
You can do everything with javascript my friend:).
This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.
<html>
<body>
<form name="LovelyForm" action="" method="post">
<input type="text" name="text1" placeholder="Text 1"> </br>
<input type="text" name="text2" placeholder="Text 2"> </br>
<input type="submit" onclick="validateForm()" value="Enter">
</form>
<script type="text/javascript">
function validateForm() {
var x = document.forms["LovelyForm"]["text1"].value;
var y = document.forms["LovelyForm"]["text2"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Fill me in");
return false;
}else{
alert("Good");
return true;
}
}
</script>
</body>
</html>
Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.
If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.
Here: Best practice as I see it :)
Only validate the most necessary on client side.
Avoid compulsory input unless they realy are.
Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.
Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/
form.elements['one'].value may cause issues if the inputs are not of type text.
The code:
<script>
function trim(str) {
if(!str) return '';
return str.replace(/\s{2,}/g, '');
}
function valid(form) {
var v1 = trim(form.elements['one'].value),
v2 = trim(form.elements['two'].value);
if (v1 === '') {
alert('one');
return false;
}
if (v2 === '') {
alert('two');
return false;
}
alert('full!')
return true;
}
</script>
<form action="/echo/json/" onsubmit="return valid(this)">
<input name="one" type="text" />
<input name="two" type="text" />
<input type="submit" />
</form>
First step is to give JavaScript an easy way to reference the element in the DOM. Generally, the easiest way is to give each element you need to reference a unique ID.
<input id="num1" />
<input id="num2" />
Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.
var val1 = i1.value;
var val2 = i2.value;
Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.
if(
// if the first value does not equal an empty string ""..
val1 != ""
// and the second value does not equal an empty string ""..
&& val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');
Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler. When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.
<form action="#" onsubmit="validate()">
<input id="num1" />
<input id="num2" />
<input type="submit" />
</form>
<script>
function validate(){
var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");
var val1 = i1.value;
var val2 = i2.value;
if(val1 != "" && val2 != "") alert("correct");
else alert("incorrect");
}
</script>

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

Set default value for Search field - Please Help!

I'm trying to set a default value for a search field. The idea is that the Search-Field has the value "Search" until the user clicks into it, then it should be empty. Also as long as it is "blank" (with "Search" as the value) it should have the class ".blank".
I tried this
<input autocomplete="off" class="" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="" />
it works so far, but when I load the site, the field is just empty. I have to click inside the field first and then somewhere on the page to make the effect working.
I guess it has something to do with onBlur. Any ideas?
Thanks!
This is known as a watermark. see http://digitalbush.com/projects/watermark-input-plugin/ for an example
Another idea is to put placeholders in your input types:
(Note this is HTML5.)
<input type=text placeholder="Default text here"/>
this way the textfield will show in a grey text color: Default text here. Once clicked it will remove the text and replace it with your current text and when its empty it comes back.
Just give it the default value 'Search' hardcoded, as in
<input ... type="text" value="Search" />
Sounds like you just need to set the initial value to Search, directly in the input tag, like so:
<input autocomplete="off" class="blank" id="searchq" name="searchq" onblur="if (this.value == '') { this.value='Search'; jQuery(this).addClass('blank'); };" onfocus="if (this.value == 'Search') { this.value=''; jQuery(this).removeClass('blank'); };" type="text" value="Search" />
Note that we also set the initial class to blank as well.
I found the problem, my mistake: onBlur is called, when the user clicks somewhere else. onLoad is only allowed for the tags BODY and FRAMESET. The solution is to set the default value somewhere serverside (for me in the application_controller, if no search term is submitted).
Thanks anyway!
blur is when a field looses focus, it cant loose focus until it has focus to begin with, hence you need to click in the field, then click out to see it working. have you tried setting the class to .blank by default ?
<input autocomplete="off" class="blank" ....
Here's a snippet I use to do this. There may be simpler ways, but this works. Any item with class .cleardefault will have it's value cleared on first mouseover. Any item with class .setcleardefault will clear the default and, if the user has not put anything in the box, reset it to the default value on mouse out.
function ClearDefault(item) {
// clear the default value of a form element
if (item.defaultValue == undefined)
item.defaultValue = item.value;
if (item.defaultValue == item.value)
item.value = '';
} // ClearDefault
function SetDefault(item) {
// if item is empty, restore the default value
if (item.value == '')
item.value = item.defaultValue;
} // SetDefault
$(document).ready(function() {
$(".cleardefault")
.mouseover(function(){
ClearDefault(this);
})
$(".setcleardefault")
.mouseover(function(){
ClearDefault(this);
})
.mouseout(function(){
SetDefault(this);
});
/*
*/
});

Categories

Resources