How to get html form to see textbox data in js - html

I have a form with 3 entries and an input submit button. One field is a textbox that prompt a numerical entry and the other 2 are selection fields. After many attempts I was finally able to get the browser to pick up on the selection options, however when i console.log it its still not seeing the numerical entry.
const submitForm = (event) => {
const form = document.getElementById('form');
const data = new FormData(form);
const dataObject = {};
for (const [key, value] of data.entries()) {
dataObject[key] = value;
};
console.log(dataObject);
return false;
}
<form name="form" onsubmit="javascript:submitForm();return false;" id="form">
<div class="dataEntry">
<div class="grossIncome">
<label for="grossIncomeEntry">Enter your gross income</label>
<input type="number" inputmode="numeric" id="incomeTextBox" placeholder="Gross Income" required>
</div>
<div class="timeframe">
<label for="perTimeframe">Per</label>
<select name="dateRange" id="incomeTimeframe">
<option value="Annual">Annual</option>
<option value="Monthly">Monthly</option
</select>
</div>
<div class="employmentLocation">
<label for="workingProvince">Where do you work?</label>
<select name="workingProvince" id="provinces">
<option value="Ontario">Ontario</option>
<option value="Quebec">Quebec</option>
</select>
</div>
<button type="submit" id="calculate">Calculate</button>
</div>
</div>
</form>

This operation:
new FormData(form)
Is essentially creating key/value pairs of form elements/values. The key is the name of the form element, and the value is its current value.
You can observe this when you see the property names in the resulting object being logged to the console. The property name for the <select> value is "dateRange". When you observe your code, where do you expect that property name comes from? Given that, what do you expect the property name for the <input> value to be and why?
Your <select> has a name, but your <input> does not. Simply add a name to it:
const submitForm = (event) => {
const form = document.getElementById('form');
const data = new FormData(form);
const dataObject = {};
for (const [key, value] of data.entries()) {
dataObject[key] = value;
};
console.log(dataObject);
return false;
}
<form name="form" onsubmit="javascript:submitForm();return false;" id="form">
<div class="dataEntry">
<div class="grossIncome">
<label for="grossIncomeEntry">Enter your gross income</label>
<input type="number" inputmode="numeric" id="incomeTextBox" placeholder="Gross Income" required name="incomeTextBox">
</div>
<div class="timeframe">
<label for="perTimeframe">Per</label>
<select name="dateRange" id="incomeTimeframe">
<option value="Annual">Annual</option>
<option value="Monthly">Monthly</option
</select>
</div>
<div class="employmentLocation">
<label for="workingProvince">Where do you work?</label>
<select name="workingProvince" id="provinces">
<option value="Ontario">Ontario</option>
<option value="Quebec">Quebec</option>
</select>
</div>
<button type="submit" id="calculate">Calculate</button>
</div>
</div>
</form>

Related

How can I pass a select HTML element as a parameter in a onSubmit form call?

I am trying to pass the html elements of a form through the submit function as parameters. I can get correctly the nameInput element with flag #nameInput, but the select element (#skillSelect) is throwing this error:
- error TS2339: Property 'skillSelect' does not exist on type 'MemberFilterComponent'.
Here is my form template. How can I pass the select element to component as I did with the input text?:
<form
[formGroup]="filterMemberForm"
(ngSubmit)="onSubmit(nameInput, skillSelect)"
>
<div class="form-row">
<div class="col-md-3">
<label class="font-weight-bold"
>Name
<input
ngDefaultControl
type="text"
class="form-control"
label="'Name'"
formControlName="name"
placeholder=" Ex: Maria Novillo"
required
id="name"
#nameInput
(change)="mapChipValue(nameInput)"
/></label>
</div>
<div class="col-md-3" *ngIf="skills.length !== 0">
<label class="font-weight-bold">Skills:</label>
<select
id="skillId"
class="form-control"
formControlName="skillId"
#skillSelect
(change)="mapChipValue(skillSelect)"
>
<option value="">-- Select skills --</option>
<option *ngFor="let skill of skills" [value]="skill.idSkill">
{{ skill.skill }}
</option>
</select>
</div>
<div class="form-row">
<div class="col-md-3 mt-5">
<button type="submit" class="btn btn-primary">Apply</button>
</div>
</div>
</form>
In the html file:
<select class='select-option'
#mySelect
(change)='onOptionsSelected(mySelect.value)'>
<option class='option'
*ngFor='let option of dropDownData'
[value]="option.seo_val">{{option.text_val}}</option>
</select>
In the ts file:
onOptionsSelected(value:string){
console.log("the selected value is " + value);
}
why you need pass the "html element"? in filterMemberForm.value you has an object with the values. Really your form should be
<form
[formGroup]="filterMemberForm"
(ngSubmit)="onSubmit(filterMemberForm)"
>
onSubmit(form:FromGroup)
{
if (form.valid)
console.log(form.value)
else
form.markAllAsTouched()
}
if you need the selectOption name always can makes
onSubmit(form:FromGroup)
{
if (form.valid)
{
//if is not multiple select
const selectedItem=this.skills.find(x=>x.idSkill==form.value.skillId)
console.log(form.value,selectedItem)
//if is multiple select
const selectedItems=this.skills.filter(
x=>form.value.skillId.indexOf(x.idSkill)>=0)
console.log(form.value,selectedItems)
}
else
form.markAllAsTouched()
}

How to disable html input readonly if user select that option?

By default the input area is set to readonly. Now I want that if user selected the Selection 3 the input area will now be inputable with text. How can I do this?
<div class="form-group">
<label for="selections">Options:</label>
<select class="form-control" id="selections" required>
<option value="sel1">
Selection 1</option>
<option value="sel2">
Selection 2</option>
<option value="sel3">
Selection 3</option>
</select>
</div>
<label for="textsection">Text to be edit:</label>
<input type="text" class="form-control" id="textsection" maxlength="34"
placeholder="User can type here if he select option 3" readonly>
you need to use Javascript, select the elements (select and the input), add an Event Listener on your select element, then you can create a function to handle this behavior. Try something like this:
const select = document.querySelector("#selections");
const text = document.querySelector("#textsection");
select.addEventListener("change", handleSelectChange);
function handleSelectChange(event) {
const value = event.target.value;
value === 'sel3' ? text.readOnly = false : text.readOnly = true;
}
You'll have to include this script in your HTML file.

Make "name" not appear on url using a <select>

I'm writing a simple form, but I've encountered a problem. The form must generate an url like this
https://website.com/properties/hotelvinadelmar?locale=es&check_in_date=22-03-2019&check_out_date=25-03-2019&number_adults=4&number_children=9
The part after /properties/ (in this case, "hotelvinadelmar") is a code for an especific hotel, while the rest is the information the customer provide to check if there's availability.
I wrote this form:
Sucursal: <br>
<select name="test" id="id" required>
<option value="hotelvinadelmar?locale=es">Viña del Mar</option>
<option value="hotelsantiago1?locale=es">Nueva Providencia</option>
<option value="hotelsantiago2?locale=es">Providencia</option></select>
<br><br>
</select>
this almost work, but generates an url like this (...)/properties/?test=hotelvinadelmar?locale=es&number_adults=1(...)
Which is creating an url structured like this
[form action (the url I entered)][Option Name][selected Option Value]
But the thing must be like this
[form action (the url I entered)][selected Option Value]
How can this be achieved? Thanks in advance!
this is the correct behavior because the submitted form data test=hotelvinadelmar will be added after the URL
(...)/properties/, in order the achieve the desired result you can try to add action attribute to your form as <form action="/hotel"> and change the select as:
<select name="hotelname" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
<br><br>
</select>
the generated link will be: (...)/properties/hotel?name=hotelvinadelmar(...)
or you can use a javascript function with onSubmit event, for example:
<script>
function submitForm(){
var hotelName = document.getElementById('hotelName').value;
var param1Value = document.getElementById('id').value;
switch(hotelName) {
case 'hotelvinadelmar':
window.location.href = '/hotelvinadelmar?param1=' + param1Value + '&param2=' + (...);
break;
case 'hotelsantiago1':
window.location.href = '/hotelsantiago1?param1=' + param1Value;
break;
}
// stop submit
return false;
}
</script>
<form onsubmit="submitForm()" method="get">
<select id="hotelName" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
</select>
<input type="submit" value="submit"/>
</form>
Capture the submission event and update the form action attribute to append the hotel name to the submission path:
document.forms[0].addEventListener("submit", function (evt) {
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
});
You'll need remove the locale property from your select input. Simply add a hidden form element (or selectable option) to your form:
<input type="hidden" name="locale" value="es">
An example url:
https://website.com/properties/hotelvinadelmar?locale=es&hotelname=hotelvinadelmar&val1=one&val2=two
Here's a demonstration how the form action attribute can be updated:
document.forms[0].addEventListener("submit", function (evt) {
evt.preventDefault(); // demonstration only
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
console.log(ff.action); // demonstration only
return false; // demonstration only
});
<form action="/properties/" method="get">
<input type="hidden" name="locale" value="es">
Sucursal:
<select name="hotelname" id="id" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option>
</select>
<input type="hidden" name="val1" value="one">
<input type="hidden" name="val2" value="two">
<input type="submit">
</form>

Using Knockout to trigger events when switching DIVs

I'm looking to trigger an event (namely, a save/cancel dialog) when switching focus between text elements--with one caveat: it's not per element, it's per containing div.
I'll have multiple divs, each with the same controls. If any values are changed in one containing div and focus is switched to another, I need to determine if the knockout data I'm leaving is dirty and then trigger the event.
Does knockout support this kind of event binding or will I have to wire something else up? It looks like I could use the tabindex attribute on my divs but I'd prefer to use existing functionality in the framework if it's available.
A mockup of the code would look like this:
<div>
First Name: <input type="text" name="firstName"/><br/>
Last Name: <input type="text" name="lastName"/><br/>
Customer Type: <select>
<option value="Individual">Individual</option>
<option value="Corporate">Corporate</option>
</select>
</div>
<div>
First Name: <input type="text" name="firstName"/><br/>
Last Name: <input type="text" name="lastName"/><br/>
Customer Type: <select>
<option value="Individual">Individual</option>
<option value="Corporate">Corporate</option>
</select>
</div>
how about something like this. kind of jquery / knockout hybrid. clicking on an attribute brings up save button. after save and moving to a different div getting focus brings up save again.
function viewModel() {
var self = this;
this.currentDiv = ko.observable('');
this.isDirty = ko.observable(false);
this.save = function() {
self.isDirty(false)
}
}
var vm = new viewModel();
(function($) {
ko.applyBindings(vm); //bind the knockout model
$("input, select").not('#save').focus(function() {
var d = $(this).parent('div').attr('id');
if (d != vm.currentDiv() || vm.isDirty()) {
vm.isDirty(true);
} else {
vm.isDirty(false);
}
vm.currentDiv(d);
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"> First Name:
<input type="text" name="firstName" />
<br/> Last Name:
<input type="text" name="lastName" />
<br/> Customer Type:
<select>
<option value="Individual">Individual</option>
<option value="Corporate">Corporate</option>
</select>
</div>
<div id="div2">
First Name:
<input type="text" name="firstName" />
<br/> Last Name:
<input type="text" name="lastName" />
<br/> Customer Type:
<select>
<option value="Individual">Individual</option>
<option value="Corporate">Corporate</option>
</select>
</div>
<input type="button" id="save" data-bind="visible: isDirty, click: save" value="save" />

Sending json data to google form with textarea and select tag

I created an application which sends json data to a google form with ajax. My problem is that I'm not able to send all the data I wish, which means that I'm not able to send some content inside a textarea and a select tag. I'm working with the url, unfortunately I had to use some hidden content in order to move some data to from a page to another page, if I wont' I'm not able to get some data.
Here is my code: The javascript:
$( document ).ready(function() {
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function postContactToGoogle() {
var full_name = getParameterByName('full_name');
var home_address = getParameterByName('home_address');
var email = getParameterByName('email');
var phone_number = getParameterByName('phone_number');
var condition = getParameterByName('condition');
var extra = getParameterByName('extra');
var when_to_sell = getParameterByName('when_to_sell');
console.log(full_name, home_address, email, phone_number, condition, extra, when_to_sell);
var google_url = "https://docs.google.com/forms/d/e/1FAIpQLSdqMQL_dzhdFSVpuVtlcfIa4xHe9DNP8yozB1ncAB2e_byBJQ/formResponse";
if (full_name !== "" || email !== "" || phone_number !== "" || home_address !== "" || condition !== "" || extra !== "" || when_to_sell !== "")
{
$.ajax({
url: google_url,
data: {
"entry.515947838": full_name,
"entry.190795925": email,
"entry.1306603567": phone_number,
"entry.1032461271": home_address,
"entry.100378601": condition,
"entry.637314286": extra,
"entry.608122467": when_to_sell
},
type: "POST",
dataType: "json",
statusCode: {
0: function () {
},
200: function () {
}
}
});
}
}
postContactToGoogle();
});
And here's the html which is creating me a lot of problem: This is a page when I'm collecting some data that I will later send with the ajax
<form action="step-3.html" id="form-step2">
<div class="form-control full-width">
<label for="condition">What conditions is the property in?</label>
<select id="condition" name="condition">
<option value="Good">Good</option>
<option value="Fair">Fair</option>
<option value="Bad">Bad</option>
</select>
</div>
<div class="form-control full-width">
<label for="extra">Any updates, amenities or extras?</label>
<textarea name="extra" id="extra" placeholder="e.g: recent reno, pool etc." rows="3"></textarea>
</div>
<div class="form-control full-width">
<label for="when_to_sell">When do you want to sell?</label>
<select id="when_to_sell" name="when_to_sell">
<option value="Immediately">Immediately</option>
<option value="Next 1-3 months">Next 1-3 months</option>
<option value="Next 3-6 months">Next 3-6 months</option>
</select>
</div>
<div class="form-control full-width">
<label>Are you currently working with a Real Estate Agent?*</label>
<input checked="checked" id="working_for_real_estate_agent_no" name="working_for_real_estate_agent" type="radio" />
<label class="radio-label" for="working_for_real_estate_agent_no">No</label>
<input id="working_for_real_estate_agent_yes" name="working_for_real_estate_agent" type="radio" />
<label class="radio-label" for="working_for_real_estate_agent_yes">Yes, I am working with a Realtor.</label>
<div class="asteriks">*We ask this to ensure there is no conflict of interest.</div>
</div>
<div class="form-control full-width">
<input id="home_address" name="home_address" type="hidden" />
<div class="home-evaluation-option-container">
<div class="home-evaluation-option">
<input id="exact-market-value" name="exact-market-value" type="button" value="Send Property Details" />
</div>
</div>
</div>
</form>
And here is the hack that I tried, which unfortunately works only with the input tag:
<form action="step-4.html" id="form-step2">
<div class="form-control full-width">
<input name="full_name" placeholder="Full Name" type="input" data-validation="length alphanumeric" data-validation-length="min1" data-validation-error-msg="Please, insert your name" />
</div>
<div class="form-control full-width">
<input id="email" name="email" placeholder="Email" type="input" data-validation="email" />
</div>
<div class="form-control full-width">
<input id="phone_number" name="phone_number" placeholder="Phone Number" type="input" name="home-phone" data-validation="number" />
</div>
<input id="home_address" name="home_address" type="hidden" class="hide" />
<select id="condition" name="condition" class="hide">
<option value="Good">Good</option>
<option value="Fair">Fair</option>
<option value="Bad">Bad</option>
</select>
<textarea name="extra" id="extra" class="hide"></textarea>
<select id="when_to_sell" name="when_to_sell" class="hide">
<option value="Immediately">Immediately</option>
<option value="Next 1-3 months">Next 1-3 months</option>
<option value="Next 3-6 months">Next 3-6 months</option>
</select>
<div class="form-control submit-button">
<input name="submit" type="submit" value="Generate Report" />
</div>
</form>
Any thought in order to collect data from a select or a text area?
Here is the page where you can find the code in action:
http://homeworth.online/hockinghomesteam/
Here is an example of how you can get the value out of a textarea element:
<!DOCTYPE html>
<html>
<body>
<textarea id="idExtra_Info">
Some content
</textarea>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("idExtra_Info").value;
alert(x);
}
</script>
</body>
</html>