If input value is blank, assign a value of "empty" with Javascript - javascript

So I have an input field, if it's blank, I want its value to be the words "empty", but if there is any value inputted, I want the value to be the inputted value. I want to use javascript for this, any idea how this can be done?
UPDATE: Sorry, I don't think I explained it too well. I don't mean placeholder text. I mean the captured value of it. So if it's blank, the captured val() for it should be "empty", if it's filled, the captured val() for it should be that val()

If you're using pure JS you can simply do it like:
var input = document.getElementById('myInput');
if(input.value.length == 0)
input.value = "Empty";
Here's a demo: http://jsfiddle.net/nYtm8/

I'm guessing this is what you want...
When the form is submitted, check if the value is empty and if so, send a value = empty.
If so, you could do the following with jQuery.
$('form').submit(function(){
var input = $('#test').val();
if(input == ''){
$('#test').val('empty');
}
});
HTML
<form>
<input id="test" type="text" />
</form>
http://jsfiddle.net/jasongennaro/NS6Ca/
Click your cursor in the box and then hit enter to see the form submit the value.

This can be done using HTML5's placeHolder or using JavaScript.
Checkout this post.

You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":
<form name="my_form" action="validate.php" onsubmit="check()">
<input type="text" name="text1" />
<input type="submit" value="submit" />
</form>
and in your js:
function check() {
if(document.forms["my_form"]["text1"].value == "")
document.forms["my_form"]["text1"].value = "empty";
}

You can do this:
var getValue = function (input, defaultValue) {
return input.value || defaultValue;
};

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.
Check this out and i will explain what it does:
<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />
So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.
Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Related

javascript input value empty after assignment

very basic question; I bet it was already asked here but really couldn't find it.
okay so I have a little html form with a hidden input:
<input type='hidden' id='switchtonew' name='new' value='no'>
and a button that shall change the value of my hidden input to 'yes', via a function because its doing a couple more things, but these work...:
<button onclick='maneu()'>switch</button>
and the function:
function maneu(){
[...]
document.getElementById('switchtonew').value = 'yes';
}
and now if you click the button, the value of my hidden input just vanishes.
why?
I did try element.setAttribute('value', 'yes'); too.
Im really confused, please help :(
EDIT: changed function name to real, used one. still not working.
You are using a reserved word switch. By renaming the function, it should work.
You could use type="button" for the button to prevent submitting.
function switchValue() {
document.getElementById('switchtonew').value = 'yes';
}
<button onclick="switchValue()" type="button">switch</button>
<!-- type is text for displaying the value -->
<input type="text" id="switchtonew" name="new" value="no">
is the button submitting a form?
Probably the page is reloading and the inputs reset, if that is the case, use an <a> instead of a <button> or add an event.preventDefault() to button action
By default button type is submit, hence:
<button onclick='yourSwitch()'>switch</button>
will submit your form, and as result, you will see yes in URL (in case you use GET form method), like:
yourhost.com/index.html?new=yes
After reload, your page will come to initial state, which is:
<input type='hidden' id='switchtonew' name='new' value='no'>
Oh man, sorry for bothering.
As it's always, you ask something and find the solution immediately by yourself.
my function is emptying a couple of inputs by looping through them, and setting styling options.
thus, I set the value to yes and immediately afterwards it deletes all values of input tags.
sorry. Im stupid.
Something like this?
function maneu() {
var currentValue = document.getElementById('switchtonew').value;
if (currentValue === 'yes') {
document.getElementById('switchtonew').value = 'no';
} else if (currentValue === 'no') {
document.getElementById('switchtonew').value = 'yes';
}
console.log('value is now: ' + document.getElementById('switchtonew').value)
}
<button onclick='maneu()'>switch</button>
<input type='hidden' id='switchtonew' name='new' value='no'>

How to set prefilled input field active with Jquery/javascript?

I'm using a calculator widget where I can enter random values into an inputfield and then the widget automatically calculates when clicking the "go"-button.
Now I want to insert/prefill the value into this input field, since the value which needs to be calculated comes from a server. The issue though is, that this input field apparently only reacts on keypress. I tried to do this:
$('input[name="value"][data-type-money]').val('150.000').focus();
and
$('input[name="value"][data-type-money]').val('150.000').select();
which prefills the input field with the desired value but when I click the "go" button the calculation fails as long I dont enter the value manually into the input field. So, in the end my solution does not work.
Does anyone know how I can solve this?
If data changes frequently you can also use the setInterval function:
<input name="value" data-type-money="money">
setInterval (function(){
var moneyValue = "150.000";
$('input[name="value"][data-type-money]').val(moneyValue);
},1000);
fiddle here: http://jsfiddle.net/85pbnnu1/
or you can just do:
$(document).ready(function(){
$('input[name="value"][data-type-money]').val('150.000').change();
});
Edit, Updated
the input field is -
and reacts only on keypress, I mean when value is entered manually
If input value property cannot be changed , try replacing the element in DOM with value set at html using .replaceWith()
$('input[name="value"][data-type-money]')
.replaceWith("<input name=value data-type-money type=text value=150.00 />")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input name="value" data-type-money type="text" />

How to take an input and when the submit button is pressed put it into a variable?

Lets say I got some HTML like this
<input type="text" placeholder="Enter Mineral">
<input type = "submit">
I have no idea how to put what is in the text into a javascript variable when the submit button is pressed. I'll use jQuery if that makes it easier.
Use .val() to fetch the value of the input field.
$("input[type=submit]").click(function(e){
e.preventDefault(); // <-------- To stop form submission
var txt = $("input[type=text]").val(); // <----- Fetch value of input field
console.log(txt) // <----------- Check console has the value of the input field.
});

jQuery - Change name of an input field by using value of another input field filled at the same time

I'm working on a dynamic form where you can add or delete fields, Here you can find the fiddle
The first button you find is Add Metric. From this the code generates:
Input Field Metric
Button Add Tag
Inside this field a user can add a tag with the button Add Tag, generated when you click add Metric. When you click Add Tag button, two fields are generated:
Input Field Id
Input Field Value
The Html code that I need to generate in order to serialize the entire form (this is not however the question point) will result like this:
<input type="text" name="metrics[0][name]" value="Text 0"> // Metric
<input type="text" id="TagId0" name=" "> //Tag Id
<input type="text" id="TagValue" name="metrics[0][tags][][0]">
Problem:
I need that (when I fill the field with id="TagId0") the value I select will go immediately to the field name with id="TagValue". This field must result like this:
Consider I write on TagId0 the word "hello", field will become:
<input type="text" id="TagValue" name="metrics[0][tags][hello][0]">
How, if it's possible, it can be done?
Thanks
You can use the change method to detect a change in the fields value. Then use the attr method to change the name. Hope I understood correctly. Here is the modified JSFIDDLE.
$(document).on('change', '#InputsWrapper .inputID', function(){
thisVal = $(this).val();
thisName = $(this).siblings('.inputVal').attr('name');
newName = thisName.replace('[tags][', '[tags][' + thisVal);
$(this).siblings('.inputVal').attr('name', newName);
});
Don't forget to press enter after change the field value :)
Edit: I also added two classes to the fields you are appending. .inputID and .inputVal. I hope this helps!
you can write id of field something like TagId-0 and some common class like tagfield,so that u can split the value to get the index an then access it using the class
$(".tagfield").keypress(function() {
var id=parseInt($(this).attr("id").split("-"));
$(this).siblings().attr("name","metrics["+id+"][tags]["+$(this).val()+"][0]");
});

Check value fields that if the same empty value in last field?

I have several field that just get number, I want if user typed be identical value in two or more field empty value the last field that is identical by jQuery.keyup?
For Example:
<input name="num[]" value="11111">
<input name="num[]" value="33333">
<input name="num[]" value="11111"> // in this input should empty value it.
How can fix it?
$(function(){
$("input").blur(function(){
var _val = $(this).val();
var change = false;
$("input").each(function(){
if($(this).val() == _val){
if(change) $(this).val("");
else change = true;
}
})
})
})
What happens if I had 12345 in a box, then I went back to an earlier box and typed 123456? The 12345 would be cleared. I suggest:
Bind the check to onchange, NOT onkeyup.
Instead of clearing the value, change the background colour to red and disable the submit button.
Adjust Yorgo's code to achieve this end, because it seems to do what you asked.

Categories