Required textarea is being highlighted in red before submitting form - javascript

Using React/Bootstrap to create a web app and have noticed a bug where when I open the form, the required textarea will be highlighted in red before I click submit.
Imgur album to show the problem (first picture is when the form is opened, second is after clicking submit) - https://imgur.com/a/g3wwekt
I tried a couple different things, and the only one that worked was to remove the required tag (but this is obviously not acceptable).
Here is the code for the textarea:
<textarea
className="form-control"
name="ticketNewDetailedInfo"
rows="5"
value={this.state.ticketNewDetailedInfo}
onChange={this.handleInputChange}
required
/>
Obviously it should only be highlighted in red if it is empty when the user submits the form.

Remove the required attribute from the textarea and handle the form validation yourself. When the form is submitted check to make sure all the fields contain values. If it doesn't since you are using bootstrap you can give the field a class of is-invalid and it will turn the input field red as a visual queue for the user. Something quick and simple to get the idea would be:
validateFormValues( values ) {
var passed = true;
for( let i = 0; i < values.length; i++ ) {
if( values[i] === '' ) {
passed = false;
}
}
return passed;
}
Then in your textarea you could write
className={ `form-control ${ !this.state.passed ? 'is-invalid' : ''}` }

this.handleInputChange is what's checking that required field. You're calling this on the onchange event. This means as soon as you click into the textarea, it is checking those required fields.
Change your trigger event to something like onsubmit instead.

Related

Updating textarea does not get submitted in form

i am developing chrome extension in google calendar.
The description of the meeting is updated through jquery as shown below,
<div class="ui-sch">
<textarea id=":24" name=":24" class="textinput" style="overflow: hidden; resize: vertical;" rows="3" aria-labelledby=":13.descript-label">
</textarea>
</div>
var el= document.getElementsByClassName("textinput");
for(i=0; i < el.length; i++)
{
if(el[i].type == "textarea")
{
el[i].value="sample description";
}
}
The content gets updated to the textarea as expected. but when we submit the form, the description is not submitted. Where as if we manually press enter after updating the content, the updated value from javascript is submitted.
I suspect, the data change in description box is binded to another variable. How to update the data change in desc to the form submission ?
update :
Steps to simulate
open calender.google.com
click create meeting paste the above
javascript in your console. (observe the value of description field)
Now click save
(the meeting description will not be saved if you open the meeting)
Now create a meeting and follow the above steps 1-3.
click on the description box and hit enter or any other character.
Save the meeting.
(The description is saved to the meeting)
In your example page, it seems as the Google API only recognizes changes when it listens a change event. You can simulate it by
el[i].dispatchEvent(new Event('change'));
not verified, just a suggestion:
if(el[i].type == "textarea")
{
el[i].value="sample description";
el[i].onchange();
}

Check form with onclick() function not working properly

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?

How to manually trigger bootstrap "required" tooltip alert?

When you submit a form via <input type="submit">
and some input with required attribute was empty, a little box appears near to the missing input box saying "Please fill out this field" or something similar (I use it in Italian so I don't know the exact wording used in English).
I need to manually trigger this tooltip alert using JavaScript, any idea how to achieve this?
The form validation is provided by HTML5, it's not related with Bootstrap, to disable the default form validation provided by the browser you have to work with the form containing the input, for example using the attribute novalidate will disable the default form validation provided by the browser. If then you want to use a custom form validation function you can use the onsubmit event on the form, so for example you will have something like:
<form onsubmit='return submitForm(this);' novalidate='novalidate'>
<input type='text' required>
<input type='submit'>
</form>
By doing this when the form is submitted you are passing the function submitForm the submitted form, so that this function is able to iterate through the elements of the form to check them.
Something like:
function submitForm(formToValidate){
var formValid=true;
var inputs = formToValidate.getElementsByTagName("input");
var errorDescription;
for(var i=0; i<inputs.length; i++)
{
var inputValid=true;
switch(inputs[i].type)
{
case "number":
if(inputs[i].hasAttribute("required")&&inputs[i].value=="")
{
inputValid=false;
errorDescription="Required field";
}
/*Check other attributes here (max, min, step, etc.)*/
break;
/*Check other types of input here*/
}
if(!inputValid)
{
markInputAsNotValid(inputs[i],errorDescription);
formValid=false;
break;
}
}
return formValid;
}
Note that the value returned by the function submitForm is used by the browser to determine if the submission was successful.
For more information: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

Disabling "save" button until at least one input field has changed

There are around 20 input fields and a save and a register buttons in a page. How can I enable a "save" button only when something changed in at least one field?
You can use Angularjs form validation:
I suppose you created a form with text inputs.
You can conditionally disable your save button (If the form is prisitine, disable the button):
<input type="submit" ng-disabled="myForm.$pristine" />
Working plunker here.
If you don't need to compare values you can just attach an event handler on key event to all text boxes and enable the save button once the event in any of them is triggered.
If you need to more "sophisticated" feature to allow saving only when some data has really changed (you may for example change "aaa" to "aa" - but then realize you want it back to "aaa") then you need to maintain the original data and compare them against any new changes and then determine whether you enable save button or keep it disabled. In such case you can for example add some sort of "original-data" attribute to your input textboxes which will hold the original value when the page is generated/loaded and on every key change event run the comparer.
Assuming your HTML looks like this:
<input>
<input>
<input>
<button class=save disabled>Save</button>
You can do something like this:
var inputs = document.getElementsByTagName("input");
var enableSave = function() {
document.querySelector("button.save").disabled = false;
for (var i = 0; i < inputs.length; i++) {
inputs[i].removeEventListener("input", enableSave);
}
};
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("input", enableSave);
}
Disabling a button for a form can be done using ng-disabled
<form name="myForm">
Name :
<input type="text" name="Name" required><br>
Age:
<input type="number" name="Age" required><br>
<input type="submit" value="Save" ng-disabled="myForm.$error.required">
here the save button is enabled only when the required fields in the form is satisfied

Disable an input field if second input field is filled

totally a newbie...
I just want to know how to dynamically disable an input field when the second input field is filled
eg:
<td><input type="text" name="num-input1" id="dis_rm" value=""></input></td>
<td><input type="text" name="num-input2" id="dis_per" value="" ></input></td>
pls... any links and hints will do...
You simply need to give it a disabled property:
document.getElementById("dis_rm").disabled = true;
document.getElementById("dis_per").disabled = true;
you can use the on change event to see if one of them is filled:
var dis1 = document.getElementById("dis_rm");
dis1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("dis_per").disabled = true;
}
}
so if the first one is filled, the second one will be disabled
$('#dis_per').blur(function(){
if($(this).val().length != 0){
$('#dis_rm').attr('disabled', 'disabled');
}
});
http://jsfiddle.net/jasongennaro/D7p6U/
Explanation:
when the second input loses focus... .blur()
check to see if it has something inside it. Do this by making sure its length is not zero !=0
if it has something in it, add the attribute disabled and set it to disabled
$('#secondinput').live('blur',function(){
$('#firstinput').attr('disabled', true);
});
tihs works when you filled the second input field and click else where ..........
Just ad this to your 2nd text box:
onblur="document.getElementById('dis_rm').disabled = (''!=this.value);"
http://jsfiddle.net/vbKjx/
Set the disabled flag on the field you want to disable when the OnBlur event fires (for exiting the field) or when the OnChanged event fires (with, of course, validation on the change).
We can ommit some steps, refering to the form as object.
document.form1.num-input2.onchange = function() {
if ( this.value != "" || this.value.length > 0 ) {
document.form1.num-input1.disabled = true;
}
}
I like this answer, using Jquery:
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
I have a search bar that gives search results with every key press, if it returns no results then the user is presented with a form to ask for help. But if they fill out the "ask form" then type in the search bar again it will erase everything they entered in the ask form. So to solve this, I gave all the inputs in the ask form an id of "second div" and the search field id="firstdiv". Now, if they click or tab to one of the input fields of the ask form it will disable to search bar so their data will never be over written.
I will also add a button that will re-enable the search form if they change their mind.
And for the newbies - I put the code in the head of the document like this:
<html>
<head>
<script type="text/javascript">
$('#seconddiv').live('focus',function(){
$('#firstdiv').attr('disabled', true);
});
</script>
</head>
<body>
....

Categories