I have a form composed of two fields.
Once the form filled, I'd like to get the two fields in a console.log that would display 'Field 1 ' + field1 + 'Field 2 ' + field2.
I know how to make it to display the value of one field but I'm getting stuck on doing this in two fields..
How would it be possible to complete this ?
Here is the HTML part :
<form name="Test">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control">
<option value=""></option>
<?php
while($data1 = pg_fetch_array($queryInv))
{
echo ("<option value=". $data1['gid'].">". $data1['gid']. "</option>");
}
?>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" id="nom-dossier-sel" name="nom-dossier-sel">
</div>
</form>
And that's the JS part :
<script>
document.getElementById('sel-inv').addEventListener('input', function() {
var field1 = this.value;
console.log ('Field 1 ' + field1);
});
</script>
Thanks for the help !
The form element has all the values with their names.
document.getElementById("form").onchange = function(e){
var form = e.target.form;
console.log(form["sel-inv"].value, form["nom-dossier-sel"].value);
}
<form name="Test" id="form">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" name="nom-dossier-sel">
</div>
</form>
This modified code will do as requested:
document.getElementById('sel-inv').addEventListener('input', function() {
var field1 = this.value;
let field2 = document.getElementById(‘nom-dossier-sel’).value;
console.log ('Field 1 ' + field1 + ' Field 2 ' + field2);
});
You can assign a custom data attribute to all field and on change of any field you can get the element by queryselector of data-field
OR
Recommended using actually id or class to get properties. You will have more control.
document.getElementById("sel-inv").addEventListener("change", function () {
const [f1, f2] = Array.from(
document.querySelector("form").querySelectorAll("[data-field='field']")
);
console.log(f1, f2);
});
<form name="Test">
<div class="form-group col-md-9">
<label for="inputState">Field1</label>
<select id="sel-inv" name="sel-inv" class="form-control" data-field="field">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="nom-dossier" class="form-group col-md-4">
<label for="exampleInputPassword1">Field2</label>
<input type="text" class="form-control" id="nom-dossier-sel" name="nom-dossier-sel" data-field="field">
</div>
</form>
Related
Basically I have this selection with some input fields:
<div class="form-row">
<div class="form-group col-lg-6">
<label>Città*</label>
<select formControlName='cittaLegale' class="form-control" id="citta_legale"
name="citta_legale" required>
<option value="" disabled selected> Scegli </option>
<option *ngFor="let comune of comuni" value="" > {{comune.Comune}}</option>
</select>
</div>
<div class="form-group col-lg-4">
<label>Provincia*</label>
<input formControlName='provinciaLegale' type="text" class="form-control"
id="provincia_legale" name="provincia_legale"
placeholder="Es.RM" value='' required maxlength="2" style="text-
transform:uppercase" >
</div>
So I did a ngFor to get all Comune from a JSON file and I need to autocomplete the input provinciaLegale (Provincia) based on I choosing the select.
This is my function to get JSON file:
listaComuni(){
this.http.get("assets/it.json").subscribe(data=>{
this.comuni = data;
})
and this is part of the JSON file:
[
{
"Istat": "028001",
"Comune": "Abano Terme",
"Provincia": "PD",
"Regione": "VEN",
"Prefisso": "049",
"CAP": 35031,
"CodFisco": "A001",
"Abitanti": 19726,
},
]
So you want to select the option and set it's value to the ProvinciaLegale input?
You could add a valueChanges hook (inside your ngOnInit()) to cittaLegale select formControl, like this:
this.formGroup.get('cittaLegale').valueChanges.subscribe(newValue => {
this.formGroup.get('provinciaLegale').setValue(newValue);
});
Im doing showing form based on user selection
the displays works well, but the value is not submitted on submit
this is my blade
<div class="form-group">
<label for="category1">Kategori</label>
<select id="category1" class="form-control" name="metas[kategori">
<option value="" disabled selected>-Pilih Kategori-</option>
<option value="motor-honda">Sepeda Motor Honda</option>
<option value="elektronik">Elektronik</option>
<option value="modal-kerja">Modal Kerja</option>
<option value="pendukung-operasional">Pendukung Operasional</option>
<option value="lainnya">Lainnya <br></option>
</select>
</div>
<div class="form-group" id="otherFieldDiv">
<label for="otherField">Isi Kategori</label>
<input type="text" class="form-control" id="otherField" name="metas[kategori]">
</div>
this is my js
<script>
$("#category1").change(function() {
if ($(this).val() == "lainnya") {
$('#otherFieldDiv').show();
$('#otherField').attr('required', '');
$('#otherField').attr('data-error', 'This field is required.');
} else {
$('#otherFieldDiv').hide();
$('#otherField').removeAttr('required');
$('#otherField').removeAttr('data-error');
}
});
$("#category1").trigger("change");
</script>
If i choose the "lainnya" value, submit function is success
but if i choose another value in the console it's returning this
metas.kategori: The metas.kategori must be a string.
I have a multidrop form at this fiddle : Here's a link! . at this form only can add multidrop 3 times, i want to make always add this multidrop, and how to save the array data into sql
<div id="Yes1">
<label for="name" >Name</label>
<input type="text" id="name1" name="name1">
<br><br>
<label for="multiDrop" >Multi Drop</label>
<select name="multiDrop1" id="multiDrop1">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
Check here to add and remove your elements as per your requirement.
You can remove only that block which you selected No for.
$(document).ready(function() {
$(document).on("change", ".multidrop", function() {
if ($(this).val() == 'Y') {
$clone = $(this).closest(".Yes").clone();
var num = parseInt($(".Yes:last").attr("data-index")) + 1;
$clone.attr("data-index", num);
$clone.attr("id", $clone.attr("id").replace(/\d+/, num));
$clone.find("input,select").each(function() {
var name = ($(this).attr("name")).replace(/\d+/, num);
var id = ($(this).attr("id")).replace(/\d+/, num);
$(this).attr("name", name);
$(this).attr("id", id);
});
$clone.insertAfter(".Yes:last"); //Add field html
} else if ($(this).val() == "N" && $(".Yes").length > 1) {
$(this).closest(".Yes").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Yes1" class="Yes" data-index="1">
<label for="name">Name</label>
<input type="text" id="name1" name="name1" class="name">
<label for="multiDrop">Multi Drop</label>
<select name="multiDrop1" id="multiDrop1" class="multidrop">
<option value="">Select Option</option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
I would recommend to use following approach:
get your repetitive block HTML into a variable;
listen for changes of drop down (using event delegation, selecting by class rather than id);
modify necessary attributes (names, id's, etc) based on global counter to distinguish those dynamic blocks;
const block = `
<div class="block">
<div class="yes">
<label>Name</label>
<input type="text" class="name"></input>
<label>Multi Drop</label>
<select class="multiDrop">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
</div>
</div>
`;
const addAnotherBlock = () => {
$('#wrapper').append(block);
$('.name:last').attr('name',i++);
};
var i = 0;
$(document).ready(() => addAnotherBlock());
$('#wrapper').on('change', '.multiDrop', function(){
if($(this).val() == 'Y') addAnotherBlock();
else if($(this).val() == 'N' && $('.block').length > 1 && !$(this).closest('.block').is('.block:last')){
$(this).closest('.block').remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper"></div>
<div class="control-group">
<label class="control-label">
<span class="red">*</span>Camera name</label>
<div class="controls">
<select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
<option>Select camera:</option>
<option>canon</option>
<option>nicon</option>
<option>sony</option>
<option>pentex</option>
<option>olympus</option>
<option>others</option>
</select>
</div>
</div>
<div class="control-group" id="dvPassport" style="display: none">
<label class="control-label">Your camera name:</label>
<div class="controls">
<input type="text" placeholder="Enter model" name="cam_name" class="input-xlarge">
</div>
</div>
javascript
<script type="text/javascript">
function ShowHideDiv() {
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = ddlPassport.value == "others" ? "block" : "none";
}
php code
$camname = $_POST['cam_name'];// user name
if(empty($camname)){
$errMSG = "Please enter camera name";
}
When i select "others" from dropdown list...it works fine
but the problem is when i select canon or nicon else...the hidden div's input tag gives error..in php code when cheking with if(empty($camname));
Have different names for select and input tags. And is good practice to add option values
<select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
<option value="">Select camera:</option> // null
<option value="canon">canon</option>
<option value="nicon">nicon</option>
<option value="sony">sony</option>
<option value="pentex">pentex</option>
<option value="olympus">olympus</option>
<option value="others">others</option>
</select>
// give a new name for this input
<input type="text" placeholder="Enter model" name="other_cam_name" class="input-xlarge">
PHP code:
$camname = $_POST['cam_name'];// cam name
$other_camname = $_POST['other_cam_name'];// other cam name
// if both select and input values
if(empty($camname) || ($camname =='others' && empty($other_camname))){
echo $errMSG = "Please enter camera name";
}else{
echo $cam_name = ($camname =='others') ? $other_camname : $camname;
}
You need to explicitly define the option values. For example:
<option value="cannon">canon</option>
JavaScript:
function myFunction() { //creating the onlick function
var locationFrom = document.getElementById("LocationFrom").value;// Getting both "from" and "to" Ids fromt he homepage.hmtl
var locationTo = document.getElementById("LocationTo").value;
if (locationFrom === locationTo) { // If both have same values then give an error as below
document.getElementById("errorLocationFrom").textContent = 'Destination cannot be the same.';
}
else {
document.getElementById("errorLocationFrom").textContent = ''; // if not the same then give no error
}
$("#Submit").click(function(){
$("#Form-2").show(); //Display form when Submit button is clicked
});
function SecForm(){
var ErrorLocation = document.getElementById("errorLocationFrom");
if(ErrorLocation == false) //Hide form2 if ErrorLocation is false
$("#Form-2").hide();
return false;
}
HTML:
<div class="full-col">
<label for="FDestination">From</label> <!---Label for select element--->
<select name="Location" id = "LocationFrom"> <!---Select element to give user options to select from-->
<option value="" disabled selected>Please Select </option> <!---Options for departing location-->
<option value="Newport">Newport</option>
<option value="Mahdi">London</option>
<option value="Cardiff">Cardiff</option>
<option value="Cilo">Brazil </option>
</select>
<label for="FDestination">To</label>
<select name="LocationTo" id = "LocationTo" >
<option value="" disabled selected>Please Select </option>
<option value="Cardiff">Cardiff</option>
<option value="Mahdi">London</option>
<option value="Newport">Newport</option>
<option value="Cilo">Brazil</option>
</select>
<!---Hidden Error message only shown when there is a validation error for departing and arrival--->
<label id="errorLocationFrom"></label>
</form>
<Form action="#" class="group" name="form2" id="Form-2" method="post" hidden = "true">
<legend id="fixed"><span class="number">2</span>Tickets</legend>
<div class="half-col">
<label for="Adult-ticket" class="center-label">Adults(+16)</label>
<input type="number" id="adult" name="user_adult">
<label id="AdTickError"></label>
</div>
<div class="half-col">
<label for="child-ticket" class="center-label">Child</label>
<input type="number" id="child" name="user_child">
<label id="ChildTickError"></label>
</div>
<input type="checkbox" id="Standard" name="Type" value="Standard">
<label class="light" for="Standard">Standard</label><br>
<input type="checkbox" id="First-Class" name="Type" value="First-Class">
<label class="light" for="First-Class">First Class</label><br><br>
<p id="total-cost"></p>
<button type = "button" value="checkout" id="checkoutbtn" onclick="AdultNumber(); calculateFare(); " >CHECKOUT</button>
</Form>
I am making a railway ticketing system and what I need, is the form to do is first be validated then after clicking the Submit button it will display the other form both forms are on the same page.
You could change the submit of form1 to input type button. When button1 is clicked you do your validation as before and if it is passed you show the form2.
In form2 you could use the onsubmit event to copy the fields you need from form1 to form2; <form id="Form-2" onsubmit="CopyData()">
In copy function you can do:
$('#Form-2').append( '<input type="hidden" name="LocationFrom" value="' + $('#LocationFrom').val() + '">' );
$('#Form-2').append( '<input type="hidden" name="LocationTo" value="' + $('#LocationTo').val() + '">' );
UPDATE - fiddle: https://jsfiddle.net/blocknotes/copyuwyd/