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'>
Related
This is my third night working on the same code... can`t get it right after days of google and tutorials and I am so tired of it... I am beeing desperate right now...
On short, I have a form and I use a button type="button" to generate a second button type="submit".
Before the second button appears, I need to check all required inputs if empty and after completion, show the second button.
I created a mixed code which now verify if inputs are empty, and highlights them one by one, not all inputs empty at the same time as I wanted.
I wanted to show highlighted all empty inputs not one by one and if one input is filled it should remove highlight class.
My work so far can be found here: here
Most important of all, I have a calculator which is calculating from inputs values. This is the reason I am using first button type="button".
How to get this to an end? I am so tired of this. Thank you.
LE: Partially fixed it by removing some return false; code from function. It has some errors although. For example, if you complete the last three inputs without completing and the ones on top, will submit anyway.
You could use the required attribute. It won't have any effects as you're not submitting the form, but then you could select all required fields with document.querySelectorAll(":required") or with jQuery $(":required") and loop through all of them validating each one.
You are returning false when a value is empty, so it's stopping the function, that's why they highlight one by one.
You can look this basic validation using JS and get idea what to do
<script type="text/javascript">
function validateMe(){
var name = document.getElementById('name').value;
var phone = document.getElementById('phone').value;
if(name==""){
//do something
alert("name can not be null");
return false;
//this will not submit your form
}
else if(phone==""){
//do something
alert("phone can not be null");
return false;
//this will not submit your form
}
else{
return true;
//This will submit your form.
}
}
</script>
<form action="somewhere.php" method="post" onsubmit="return validateMe();" >
<input type="text" name="name" id="name" />
<input type="text" name="phone" id="phone" />
<input type="submit" value="check and submit" />
</form>
NOTE: This is very basic validation using Javascript. What you want is to click one button and if valid then show submit button. But why you want do that if you want only validation. Why two buttons one to check values and show submit button and another button is submit itself. Why?
I created another short loop function BUT after inputs are filled, newButton button does not show. All Inputs are turning green from empty red. Please see the positioning of the return false;
function validateForm() {
var elements = document.getElementsByClassName("form-calc");
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
elements[i].style.borderColor = "red";
} else {
elements[i].style.borderColor = "green";
return false; // IF PUT THIS HERE, ONLY ONE INPUT AT A TIME IS HIGHLIGHTED BUT IN THE END THE newButton WILL POP UP.
}
}
return false; // iF I PUT THIS HERE IT STOPS HERE, NO NEWBUTTON NEXT.
var newButton = "<input type='submit' name='submit' value='Trimite-mi oferta pe mail' class='buton-calc'/>";
document.getElementById("a").innerHTML= "<span style='margin-left: 17%;'>Oferta personalizată a fost generată</span>"+newButton;
//SOME CODES HERE
});
What am I missing?
I know it's simple and there's probably something wrong with my syntax but I just don't understated it. I'm talking about the following:
//declaration of a string
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
str_input = $('input[name=po]').val();
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
That's it, can you help me to sort it out? The problem so far is that str_input is undefined regardless of what is written in the input, though, it saves its initial value.
Your html tag is invalid:
<input type"text" name = 'po' id="po" value="asd">
Should be:
<input type="text" name = 'po' id="po" value="asd">
// ^ Missing this character (=)
Ok, Now I understood, you can do 2 things, first, you can create a button than when the user clicks it calls the function to store the value in the variable like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$("#MyButton").click(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
<input type="button" id="MyButton" value="Click Here" />
Or the blur function when the user lose focus of the input text like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$('input[name=po]').blur(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
Ok, so here is the solution, though it's a little bit in "from Alf to Alf" style. So, yes, the code I've posted in the main post uses correctly the 'by default' value of the input but the problem comes from that nothing is checking for further changes in the input text field. I'm using $(document).ready... which as far as I know runs during the web project is opened and of course enables the use of some jquery methods within it. There is an interesting function called .change() which actually put the whole thing up for me. Take a glance at the following:
$(document).ready(function(){
$('input[type="text"]').change(function(){
str_input = $('input[name=polynom]').val();;
});
str_input = $('input[name=polynom]').val();
});
The second, third and fourth line make the magic actually, where the code in the .change() method updates str_input on each time a change have appeared in the input box field, whereas the str_input = $('input[name=polynom]').val(); outside of change() takes into account the initial value of the input. That's it... I knew I was forgetting something and yeah...
P.S. Another approach is to use a function and a button (a.k.a. an event-triggered function) which to 'update' the str_input on event. For this way check the post bellow this one.
Beginner level with Javascript and have a question regarding the input type color.
I am trying to make the user choose the color black before proceeding with next page of the form. The default color is yellow.
Could someone please help me with this and explain where I have gone wrong or missing something?
And have done research to try figure it out myself but stuck, probably the simplest thing as per normal. Thanks
Here is a snippet:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.style.backgroundColor =='rgb(255, 153, 153)') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
}
function spamCheck() {
//alert("Spam Check Working.......");
var color = document.getElementById("color").value;
if (!color == "#000000") {
alert("Please enter the color black to proceed.");
color.focus;
return false;
}
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<button type="submit" onClick="validate(), spamCheck()">Continue → </button>
</span>
</form>
There a couple of things to be improved here as the logic does not really add up. Heres your code, amended and annotated with comments:
function validate() {
var elements = document.getElementById("form1").elements;
for (var i = 0, element; element = elements[i++];) {
// When using the `not equal` operator, use it _in the operator_.
// Putting a `!` in front of a variable will change the variable first
// before comparing. This can cause unexpected issues!
// Also added a type check as the button does not have a value of
// '#000000', so the alert would _always_ show. This prevents that.
if (element.type === 'color' && element.value !== '#000000') {
alert("Please enter data for any fields highlighted in red");
return false;
}
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
function spamCheck() {
// As you want to focus on this element later, store the element
// NOT the value.
var color = document.getElementById("color");
// This is the point where the placement of the `!` is changed
// Because if you invert the value of a string, you might get
// unexpected results!
if (color.value !== "#000000") {
alert("Please enter the color black to proceed.");
// Focus is a _method_ of an <input> node,
// not a property, so call it with ().
// Also, because you originally set color to the _value_,
// it is only a string and not the <node>
color.focus();
return false;
}
// to allow your HTML prevention of submission, make sure to always return a boolean value.
return true;
}
<form id="form1">
<span class="center">Spam Check. What colour is black? (choose a colour)
<input name="color" id="color" type="color" value="#FFFF00" />
</span>
<span class="button">
<!-- To prevent submission, your onclick is changed -->
<button type="submit" onClick="return (validate() && spamCheck())">Continue → </button>
</span>
</form>
Please note that your validate() will always throw an alert as your button does not have a value of #000000, which is also considered an element. Therefor not all elements pass your test. However, I have amended this by checking if the elements type is that of color, and only then checking for that value and alerting.
But here's the main issue: how do you do this properly? Well, javascript uses event listeners for that, and it could greatly improve your code. I have added my suggestion to the snippet below. Keep in mind that attaching events to HTML elements using onSomething attributes on elements is considered bad practise. That's mostly because it makes your code too tightly coupled together, meaning that if you have to amend it later it will be a mix of JS, HTML and other elements thrown in and it will become confusing.
Event Listeners solve that issue for you, you can attach them to the element using only javascript, but that does mean that your form can be subm,itted without javascript. That's technically what you want - but keep in mind that SPAM bots usually disable javascript anyhow, so nothing of what you do has any affect unless you write your form using only javascript.
Now, onto an improved version of the provided code that is not as tightly coupled. I added some properties to your HTML (and removed other just to make it simpler but you can keep the spans, for example). These properties are not tightly coupled to JS. They are there for JS to read, but make no difference otherwise. It also means someone who only knows HTML can edit the messages.
The checkColor is now also rolled into your validation function, as is validation to anything. Now even better would be to check using regex patterns, but that's beyond the scope of this question.
var form = document.getElementById('myForm');
// Only run this function when a submit button is clicked and the form is
// considered to be submitted. Pass the function an event as well.
form.addEventListener('submit', function(event){
// Lets assume the form is valid
var isValid = true;
// Lets use a standard for loop, it's easier to read
for(var i = 0, element; element = form.elements[i]; i++){
// I;ve added two data-properties in your HTML, one that tells us what
// value your are looking for and another that provides the hint
// you want to show people
var match = element.getAttribute('data-match');
var hint = element.getAttribute('data-hint');
// If there is something to match and it does not match the value provided
// then set isValid to false and alert the hint (if there is one);
if(match && match !== element.value){
isValid = false;
if(hint) alert(hint);
}
}
// If one element has set the isValid to false, then we want to prevent
// the form from actually submitting. Heres were the event comes into play:
// event.preventDefault() will stop the form from actually submitting.
if(!isValid) event.preventDefault();
});
<form id="myForm">
<input name="color" id="color" data-hint="Enter the color black in HEX to proceed." data-match="#000000" type="color" placeholder="#000000" />
<input type="submit" value="Continue →" />
</form>
Just use change the if statement to look like this if (color !== "#000000")in the spamCheck functtion now we can check if the color is the correct value.
here is an example try to change the color to black and the alert will change.
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.
I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}