REQUIRED || REQUIRED HTML5 Forms - javascript

I have arrived to a situation that if only one of the two required fields in the form are filled then it should submit the form. Unfortunately, if i put required on both the fields it would wait for both of them to be filled in. Can this work without using JS? I know it is nearly impossible while not knowing any of the hidden features regarding it?

Can this work without using JS?
No, you need JavaScript to do that validation client-side.

The solution requires JS, but is easy - simply toggle the .required property of the elements based on whether either of them has a value:
var t1 = document.getElementById('test1');
var t2 = document.getElementById('test2');
function toggleRequired() {
t2.required = (t1.value.trim() === '');
t1.required = (t2.value.trim() === '');
}
t1.addEventListener('change', toggleRequired, false);
t2.addEventListener('change', toggleRequired, false);
<form>
<input name="test1" id="test1" required />
<br/>
<input name="test2" id="test2" required />
<br/>
<input type="submit" />
</form>

You could also put it into one div. It did worked for me.
<form>
<div class=question>
<input id="field1_1" name="field1" required>
<input id="field1_2" name="field1" required>
<input type="submit" />
</div>
</form>

Related

Angular validations - Enabling/Disabling input fields changes validity of form

I have a form. In which I have input fields and I am doing some validation based on input. Also, there is a submit button which enables only if form is valid.
In this form I am enabling/disabling input field in one of the flow.
Initially, when the fields are enable and empty, create button is disabled. After i disable and enable the fields, create button becomes enabled. Although input fields are still empty.
More over button which is enabling/disabling this part is outside of this form.
Here is my code
`
<form method="post" novalidate id="example-widgets-form" name="mdnsCtrl.createSubDomainForm" valdr-type="SubDomain">
<div>
<label>Domain Name</label>
<input required type="text" name="subDomainName" placeholder="Domain Name" ng-model="mdnsCtrl.newDomain.name">
</div>
<div>
<label>Description</label>
<input type="text" name="subDomainDescription" placeholder="Description (Optional)" ng-model="mdnsCtrl.newDomain.description">
</div>
<button type="button" aria-label="Create" ng-click="mdnsCtrl.createDomain();"
ng-disabled="mdnsCtrl.createSubDomainForm.$invalid">
<span class="ng-scope">Create</span>
</button>
</div>
</form>
Tried few things like using $setUntouched() and $setPristine(). But nothing is working. Any help will be appreciated.
Adding a codepen example for this: code
Much Thanks.
`
Its not good practice to mix Angular with jQuery. Please read this great post: “Thinking in AngularJS” if I have a jQuery background?
You can easily achieve requested behavior by using ng-disabled="mdnsCtrl.formDisabled"
JS
var ctrl = this;
ctrl.formDisabled = false;
this.disable = function(){
ctrl.formDisabled = true;
};
this.enable = function(){
ctrl.formDisabled = false;
};
HTML
<div>
<label>Domain Name</label>
<input class="input-field" required type="text" name="subDomainName" placeholder="Domain Name"
ng-disabled="mdnsCtrl.formDisabled"
ng-model="mdnsCtrl.name" >
</div>
<div>
<label>Description</label>
<input class="input-field" type="text" name="subDomainDescription"
ng-disabled="mdnsCtrl.formDisabled"
placeholder="Description (Optional)" ng-model="mdnsCtrl.description">
</div>
Fixed Demo Codepen
I think you missed required attribute for Description input..
<input type="text" name="subDomainDescription" required ng-model="mdnsCtrl.newDomain.description">

HTML form action search, one text box, 2 buttons, 2 possible results

I am trying these days to do a search form that sends to two different pages with two different buttons with a single text box. So far I am doing this:
<form action="http://www.youtube.com/results" method="get">
<input name="search_query" type="text" maxlength="128" />
<input type="submit" value="YouTube" />
</form>
<form action="https://torrentz.eu/search" method="get">
<input name="q" type="text" maxlength="128" />
<input type="submit" value="TorrentZ" />
</form>
of course the result is this:
I can work with that, but I want to make it "cuter" like this:
So far I have tried using a script but I did not get it so I scraped it, then I tried making an if/elseif but yet again, I was not sure what I was doing, I am not a good planner for what I see, a toggle button or a dropbox is not as fast, as I just need to press tab once or twice and enter to just search where I want.
As an extra note, I am just making my personal "new tab" for chrome, as the basic and the ones I find in extensions are pretty heavy for my mini laptop.
In HTML5 you can use formaction attribute.
<!DOCTYPE html>
<html>
<body>
<form>
<input name="search_query" type="text" maxlength="128" />
<input type="submit" formaction="http://www.youtube.com/results" value="YouTube" />
<input type="submit" formaction="https://torrentz.eu/search" value="TorrentZ" />
</form>
</body>
</html>
Since you tried and failed a script, let's look at ways we can achieve this.
Using form
Be extremely wary of what you do here. It is easy to send a get request using form but it always "flushes" out the query strings already present in the action URL, and submits the request by adding name-value pairs in its child nodes. Make sure to create your query as a child node.
<input type="text" id="box" name="searchbox" maxlength="128" placeholder="Type text to be searched here" autofocus />
<input type="button" value="Youtube" onclick="search_youtube()"/>
<input type="button" value="Torrentz" onclick="search_torrentz()"/>
<script>
function search_youtube(){
var add="https://www.youtube.com/results";
var box = document.getElementById("box");
box.name="search_query"
if(box.value)
{
var form = open().document.createElement("form");
form.action=add;
form.appendChild(box.cloneNode(false))
form.submit();
}
}
function search_torrentz(){
var add="https://www.torrentz.com/search";
var box = document.getElementById("box");
box.name="q"
if(box.value)
{
var form = open().document.createElement("form");
form.action=add;
form.appendChild(box.cloneNode(false))
form.submit();
}
}
</script>
Using HTML5 formaction attribute
<form action="https://www.youtube.com/results" method="GET">
<input type="text" id="box" name="search_query" maxlength="128" placeholder="Type text to be searched here" autofocus />
<input type="submit" value="Torrentz" formaction="https://www.torrentz.com/search" onclick="document.getElementById('box').name='q'" />
<input type="submit" name="submit" value="Youtube" />
</form>

Save form data to local storage with JavaScript in a Phonegap application

I have a simple form that I would like to accept data with and store each input as a local storage variable used as a one time setup.
Here is my current JavaScript and HTML form:
<script type="text/javascript">
function accountSetup(form){
localStorage.payDayDate = form.setPayDayDate.value;
localStorage.monthlyTakeHome = form.setMonthlyTakehome.value;
localStorage.monthlySavingsTarget = form.setSavingsTarget.value;
console.log("set up complete again");
}
</script>
I have also tried document.getElementById("setPayDayDate").value(); if you think the syntax is incorrect.
<form>
<label>
Date of pay day:
<input type="text" id="setPayDayDate" placeholder="23" />
</label>
<label>
Monthly takehome:
<input type="text" id="setMonthlyTakehome" placeholder="£800" />
</label>
<label>
Savings target:
<input type="text" id="setSavingsTarget" placeholder="£200" />
</label>
<input type="submit" value="Calculate" onClick="accountSetup(this.form)" />
</form>
I also assume that since I haven't set a method or action that the page will just refresh but the localstorage variables will have been set? I do have divs that are meant to display the newly set variables but they still appear empty after the form submission.
Is there some kind of common practice im missing? Any advice is appreciated, thanks.
Update
There are no messages/errors in the console log
Ok so there were quite a few things wrong with this. My first clues came from this very good youtube video:
https://www.youtube.com/watch?v=BVo3nnloZzw
Using what I learnt there I was able to successfully collect, store and then represent the form data. Here is the updated code:
<script type="text/javascript">
function accountSetup(){
var submittedPayDayDate = document.getElementById("setPayDayDate").value;
var submittedMonthlyTakehome = document.getElementById("setMonthlyTakehome").value;
var submittedSavingsTarget = document.getElementById("setSavingsTarget").value;
window.localStorage.setItem("payDayDate", submittedPayDayDate);
window.localStorage.setItem("monthlyTakehome", submittedMonthlyTakehome);
window.localStorage.setItem("monthlySavingsTarget", submittedSavingsTarget);
return false;
}
</script>
<form method="post" onSubmit="return accountSetup()" data-ajax="false">
<label>
Date of pay day:
<input type="text" id="setPayDayDate" name="setPayDayDate" placeholder="23" />
</label>
<label>
Monthly takehome:
<input type="text" id="setMonthlyTakehome" name="setMonthlyTakehome" placeholder="£800" />
</label>
<label>
Savings target:
<input type="text" id="setSavingsTarget" name="setSavingsTarget" placeholder="£200" />
</label>
<input type="submit" value="Calculate!" />
</form>
To then use the collected data use this line code:
window.localStorage.getItem("varName");
I hope this turns out to be useful for someone.
Use name="setPayDayDate" instead-of/in-addition-to the id="" on your form inputs.

What is the most efficient way of submitting a form whose inputs are not direct children of the form element itself using native JavaScript?

I am currently creating a form for my employer which tracks individual employee statistics throughout a typical day, such as number of calls, revenue, items sold, etc. I would like to asynchronously update a database using a simple html form without necessarily having to use the entire jQuery library since all I would be using is the $.ajax method, which I do know is effective.
The trouble I'm running into is in finding a way to serialize a form using the form's <input type="submit"> button. My form's input fields are spatially organized using <div></div> tags between the <form> element itself and its <input /> fields themselves, as seen below:
<form name="tour_1" id="tour_1">
<div class="num_calls_cell">
<input type="text" value="3" name="total_calls" autocomplete="off" />
</div>
<div class="acw_cell">
<input type="text" value="24.35" name="acw" autocomplete="off" />
</div>
<div class="rev_cell">
<input type="text" value="125.34" name="revenue" autocomplete="off" />
</div>
<div class="env_cell">
<input type="text" value="0" name="envelopes" autocomplete="off" />
</div>
<div class="pen_cell">
<input type="text" value="1" name="pens" autocomplete="off" />
</div>
<div class="cal_cell">
<input type="text" value="0" name="other" autocomplete="off" />
</div>
<div class="comment_cell">
<input type="text" value="comment" name="comments" autocomplete="off" />
</div>
<div class="submit_cell">
<input type="submit" class="submit_tour" value="Submit Tour" />
</div>
</form>
There are a total of four of these forms that I have in one "day" (you may view the actual project here (http://ryanvold.com/prototype/prototype.php).
How could I most effectively transfer my form data into a PHP file that can easily update a MySQL database using my <input type="submit"> buttons?
You can serialize form like this:
document.getElementById('tour_1').addEventListener('submit', function(e) {
e.preventDefault();
var params = [];
for (var i = 0; i < this.elements.length; i++) {
params.push(this.elements[i].name + '=' + encodeURIComponent(this.elements[i].value));
}
params = params.join('&');
alert(params);
}, false);
This will give you params as follows:
total_calls=3&acw=24.35&revenue=125.34&envelopes=0&pens=1&other=0&comments=comment&=Submit%20Tour
Having constructed params string like this you can use it as ajax request POST parameters:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
This is just an example, remember to take care of IE if you need to support it (attachEvent).
Demo: http://jsfiddle.net/LnLaT/

jQuery Radio Button function not working properly

I have a form with two radio buttons and a submit button which leads to a specific form based upon the user's selection.
I wanted to use jQuery to change between the two buttons but have gotten myself a bit lost.
Here is my javascript from another file in the proj:
function goTo()
{
var yesButton = $('#yesRad');
var noButton = $('#noRad');
if (yesButton[0].checked)
{
submitForm('yesForm') && noButton.Checked==false;
}
else (noButton[1].checked)
{
submitForm('noForm') && yesButton.Checked==false;
}
Inside the jsp I have the following code:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name ="radio"id="yesRad" value="yesForm" checked="checked" />Yes<br>
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
<input type="hidden" name="mode" value="1" />
<input type="radio" name="radio" id="noRad" value="noForm" />No<br>
</form:form>
Submit
<script>
$("#yesRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked'))
$("#yesRad").prop("checked", false);
else if($input.is(':checked'))
$("#yesRad").prop("checked",true) && $("#noRad").prop("checked",false);
});
</script>
I have gotten some functionality out of my jQuery but it's definitely far from correct..
I hope I was clear and thorough in my question. Thanks in advance!!
To begin with, don't use prop, use attr. prop is slower.
You've defined variables so let's not look them up again. In your if/else statement just use the variables.
I'm not entirely sure what you're trying to do with the &&. I suspect you're trying to set the value of the two inputs. If so, they should be separate statements. If inputb is checked there is no reason to set it to checked, so we can remove that piece.
You probably want this change to fire on both inputs.
$("#yesRad, #noRad").change(function(){
var $input = $("#yesRad");
var $inputb = $("#noRad");
if($inputb.is(':checked')){
$input.attr("checked", false);
} else if($input.is(':checked')){
$inputb.attr("checked",false);
}
});
Solved: Using javascript and taking the radio buttons out of the separate form elements.
First let's take a look at the JSP form elements involved:
<form:form action="interested" commandName="user" name="yesForm" id="yesForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<form:form action="notinterested" commandName="user" name="noForm" id="noForm">
<input type="hidden" name="state" value="<c:out value="${requestScope.state}"/>" />
<input type="hidden" id="address" name="address" value="${user.address}" />
</form:form>
<input name="radio" type="radio" id="Yes" value="yes" />Yes<br>
<input name="radio" type="radio" id="No" value="no"/>No<br>
What I did here was simply take the radio buttons out of the separate forms and grouped them together...pretty obvious; now let's look at the javascript file.
function goHere()
{
var yesButton = $('#Yes');
var noButton = $('#No');
var str ="Please select an option first then press the 'Submit' button";
if (yesButton[0].checked)
{
submitForm('yesForm');
}
else if (noButton[0].checked)
{
submitForm('noForm');
}
else
{
document.write(str.fontcolor.font("red"));
}
}
As you can see the function 'goHere();' is going to tell the submit button in the following code where we want to go based on the user's selection on our radio buttons.
Here's the call from our javascript function in a submit button on the form...
<div class="button-panel" id="Submit"><span class="buttons buttons-left"></span>
<button type="button" class="buttons buttons-middle" name="submitBtn" onClick="goHere();">Submit</button>
<span class="buttons buttons-right"></span>
That's it!! Simply put; sometimes, while it's invaluable to learn something new, if it's not broke--etc. Hope this helps someone later on down the line!

Categories