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
Related
I have 3 different forms on a single page where the user can switch between using JS. The forms represent different information and only one can be submitted at a time where the user is then redirected to a different page based on the form they selected. The issue is that I have 2 input fields that are common to these forms so they are outside the forms. I am able to submit them alongside a form if I set the :
<input id="default" form="form1">
value.
So I figured it would be a simple thing to just add a function in each script where I hide/show the forms to also change that parameter to the form I want submitted however it doesn't seem to work.
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.form = "form2";
}
I have something like this but it doesn't change the form parameter.
You need to actually give your input an ID of default so you can target it:
<input form="form1" id="default">
use setAttribute
function form2Search() {
$('#form2Section').show();
var input1 = document.getElementById('default');
input1.setAttribute("form", "form2");
console.log(input1.getAttribute("form"))
}
form2Search();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="default" form="form1">
I was wondering if it is possible to have an input field that has a bit of text added to it after the user enters the information they want. EX. a user types youtube.com into a search bar, and the input applies https://www.
You could use an event listener that will change the value of the input field.
Use RegEx to find out if the string (https://www.) has been set before (for instance by copying and pasting the URL).
Here is an example:
document.getElementById('url').addEventListener('keyup', (e) => {
if (!/^(https:\/\/www.)/.test(e.target.value) && e.target.value) {
e.target.value = `https://www.${e.target.value}`;
}
});
<input type="text" id="url">
use blur event
you can run a function after a user leaves the input field
see https://www.w3schools.com/jsref/event_onblur.asp
You need to manipulate the user input for that use javascript. If user presses submit button then don't submit input immediately use event.preventDefault() to stop default action and then change user input if needed after that manually submit it using AJAX.
function manuallySubmit(event){
event.preventDefault();
// manipulate input here
var input = document.getElementById("input").value;
input = "changed value " + input;
console.log(input);
/* AJAX POST request
let xhr = new XMLHttpRequest();
xhr.open('POST','location',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8');
data = 'input='+(input);
xhr.send(data);
*/
// window.location.href="newlocation" if you want to redirect
}
<form onsubmit="manuallySubmit(event)" action='#' method="POST">
<input type="text" name="input" id="input" /><br/>
<input type="submit">
</form>
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.
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
I've got a HTML form that has two possible types ("id" or "profile")
<form action="process.php">
<input type="radio" name="type" value="id">
<input type="radio" name="type" value="profile">
<input type="text" name="value" value="input">
</form>
So essentially, my resulting URL is
/process.php?type=id&value=input
(or type=profile, depending on what the user picks)
What I want is my URLs to look something like
/process.php?id=input
or
/process.php?profile=input
I have two questions:
1) Is the following jQuery/JavaScript code "bad practice"? I really don't feel like I'm doing it correctly if I do it the following way (even though it works):
<input type="submit" onclick="formSubmit()">
<script>
function formSubmit() {
// if the first radio (id) is selected, set value name to "id", else "profile"
$("form input:text")[0].name = $("form input:radio")[0].checked ? "id" : "profile";
// disable radio buttons (i.e. do not submit)
$("form input:radio")[0].disabled = true;
$("form input:radio")[1].disabled = true;
}
</script>
2) Is there a way to do this without using htaccess rules or JavaScript?
Thanks!
As for your first question, I'd write my jQuery like this:
// store your form into a variable for reuse in the rest of the code
var form = $('form');
// bind a function to your form's submit. this way you
// don't have to add an onclick attribute to your html
// in an attempt to separate your pre-submit logic from
// the content on the page
form.submit(function() {
// text holds our text input
var text = $('input:text', form),
// radio holds all of our radio buttons
radio = $('input:radio', form),
// checked holds our radio button that is currently checked
checked = $('input:radio:checked', form);
// checking to see if checked exists (since the user can
// skip checking radio buttons)
if (checked) {
// setting the name of our text input to our checked
// radio button's value
text.prop('name', checked.val());
}
// disabling our radio buttons (not sure why because the form
// is about to submit which will take us to another page)
radio.prop('disabled', true);
});
As for your second question, you could always move this logic to the server side. It depends if you want the pre-processing logic to be done by the client, or by your server. Either way you should have logic on the server to validate the form. If your js errors out, it could send over the raw form data. Personally I'd put this logic on the server to avoid the overhead of checking to make sure it was pre-processed in the first place. You'll also be able to cut down on your js use which will save you some precious bandwidth.
You could try something like this:
<input type="radio" name="type" value="id" onclick="getElementById('textValue').setAttribute('name','id');">
<input type="radio" name="type" value="profile" onclick="getElementById('textValue').setAttribute('name','profile');">
<form action="process.php">
<input type="text" id="textValue" name="value" value="input">
<input type="submit">
</form>
Put the radio inputs outside the form, have the text input identified by an id so you can use the getElementById function (still needs to be checked if it is supported by the browser). This avoids loading jQuery if you don't need it on this page.
The result is the one expected by you.
But.. I would use server-side processing of the form.