How can I build multiple step selectors in HTML page? - javascript

I have a problem with HTML contact form.
For example I have that schema with element dependencies:
Where are many selectors and inputs depends on what is selected in previous steps.
How can I build that logic in HTML and Javascript (Jquery)?
For result I need to return one input hidden field, where are placed all selected values, for example:
Cash - at Compensa partners - Outside Riga - Serviss from selected option
Maybe there are some Jquery solutions for that purpose?
P.S. I can only use HTML pages

Minimal example: write out all the different selects and only show the relevant one. You can add all the other dependencies in a similar way. Building the selects dynamically will be less, but more complicated code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example</title>
<style>
.hide {
display: none;
}
.show {
display: block;
}
</style>
</head>
<body>
<div id="claim">
<select>
<option value="default" disabled="disabled" selected="selected">Select a claim type</option>
<option value="cash">Cash</option>
<option value="repair">Repair</option>
<option value="glazing">Glazing</option>
</select>
</div>
<div id="cash" class="hide">
<select>
<option value="partners">At Compensa partners</option>
<option value="office">Compensa Office</option>
<option value="broken">Verhicle is broken</option>
</select>
</div>
<div id="repair" class="hide">
<select>
<option value="age">Car age</option>
<option value="place">Serviss place</option>
</select>
</div>
<script>
var dependencies = {
'claim' : {
'cash' : 'nextDep',
'repair' : 'nextDep',
'glazing' : 'nextDep'
}
};
document.querySelector('#claim select').addEventListener('change', function ( event ) {
var parentID = event.target.parentNode.id,
value = event.target.value;
Object.keys(dependencies[parentID]).forEach(function ( key ) {
var select = document.querySelector('#' + key),
currentClass = select.className;
if (select.id === value && currentClass === 'hide') select.className = 'show';
else if (currentClass !== 'hide') select.className = 'hide';
});
});
</script>
</body>
</html>

Related

How to validate dynamic select DropDown using html and javascript?

I have a form having education details in which there is a dropdown which gives 4 option
schooling
graduation
post graduation
others
now what I am doing is allowing user to fill those details but what I want is user can not select one education type more than once which means user can select schooling once,graduation once and so on and this validation i want on client end which is js/jquery
image for reference
function checkUserEducation() {
const userSelectedEducationArray = $("select[name='educationType[]']").map(function() {
return $(this).val();
}).get();
//checks if any education type is empty
if (userSelectedEducationArray.includes("")) {
$('#educationErrorMsg').show();
} else {
$('#educationErrorMsg').hide();
}
if (countElement('schooling', userSelectedEducationArray) > 1) {
// $('#educationErrorMsg').show();
$('#educationErrorMsg').after("*schooling can be chosen only one time");
} else {
}
if (countElement('graduation', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').after("</br>*graduation can be chosen only one time");
} else {
}
if (countElement('post_graduation', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').after("</br>*post graduation can be chosen only one time");
} else {
}
if (countElement('others', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').html("</br>*others can be chosen only one time");
} else {
}
}
function countElement(item, array) {
var count = 0;
$.each(array, function(i, v) { if (v === item) count++; });
return count;
}
this validation i am trying to do but i am not getting appropriate outcome
so any help regarding this
<select class="form-control" id="educationType" name="educationType[]" aria-label="Select Education Type">
<option selected value="">Select type</option>
<option value="schooling">Schooling</option>
<option value="graduation">Graduation</option>
<option value="post_graduation">Post Graduation</option>
<option value="others">Others</option>
</select>
this is my select dropdown on which i want validation
so any hints or validation tips would be very helpful
THANK YOU !!
English is not my primary language but i'll try my best to explain.
Give same class to all selects that you want to check
then on change function loop through all element with given class
if you're using form-repeater then compare name of the elements to avoid comparing with the same element. if you are not using form-repeater add a "data-counter" element add increase its value on every new add,
after that just compare value of the element, if same then show alert
var count = 1;
$(document).on("click", ".add-btn", function () {
$("#clone")
.find(".gg").addClass('test-select')
.attr("data-counter", count++);
$("#Main").append($("#clone").html());
$("#clone")
.find(".gg").removeClass('test-select');
});
$(document).on("change", ".test-select", function () {
const This = $(this);
$(".test-select").map(function() {
if(this.getAttribute('data-counter') !== $(This).attr('data-counter')){
if($(this).val() == $(This).val()){
alert('repeat');
$(This).css('background-color','red')
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>stack question</title>
</head>
<body>
<div id="Main" class="row p-1">
<div class="col-md-8">
<select class="form-select test-select" data-counter="0" name="test[]" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary add-btn">Add</button>
</div>
</div>
<div class="d-none" id="clone">
<div class="mt-2"></div>
<div class="col-md-8">
<select class="form-select gg test-select" data-counter="" name="test[]" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary add-btn">Add</button>
</div>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$("#educationType").change(function(){
if($(this).val() && !$(this).find('option:selected').attr("data-clicked")){
$(this).find('option:selected').attr("data-clicked","true")
}else if($(this).find('option:selected').attr("data-clicked")){
alert(`"${$(this).val().toUpperCase()}" can be chosen only one time`);
$(this).val("")
}
})
</script>

How do I change the select option value contents using js

I'm not good at javascript but I tried this...
I'm trying to make an option for a user to switch to another page after searching for an item.
The user for example will searches for a Mercedes under cars section then the options value can change to the Mercedes links page as well as can change to GMC links page is the user searches for gmc. This code seems not to work.
Below is the code:
<div class="all" id="note">
Some content will be posted here...
</div>
<select id="marketing" onChange="window.open(this.value)" multiple>
<option value="1">cars</option>
<option value="2">houses</option>
<option value="3">Promotion</option>
</select>
<script type="text/javascript">
var cars = ['mercedes']
$('#marketing').change(function(){
if($(this).val() == '1'){
if cars[0] ==='mercedes';{
$(this).val() == "http://www.cars.com/mercedes";
}
}
});
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var cars = ['mercedes']
function myFunction() {
var x = document.getElementById("marketing").value;
var companey = document.getElementById('companies').value;
console.log(x + companey);
if (x == 1 && companey == "mercedes") {
var url =
window.open("http://www.cars.com/mercedes" , '_blank');//for new tab
//for same tab
//window.open('http://www.cars.com/mercedes');
}
}
</script>
</head>
<body>
<!this is a working sample hope this will help>
<div class="all" id="note">
Some content will be posted here... <br />
<input type="text" id="companies">mercedes</input>
</div>
<select id="marketing" onchange="myFunction()">
<option value="0"></option>
<option value="1">cars</option>
<option value="2">houses</option>
<option value="3">Promotion</option>
</select>
</body>
</html>

Problem with dynamically adding questions via add button on page

So this is my form creator which will be used to generate forms in django. Basically this is a dynamically generate django "FormView" . So now the problem is when the user will remove a question from the UI the Question's numbering won't reorder automatically. I need those numberings because on the backend those will be used by django to create a form by mapping this data received to actual models.CharField and other corresponding fields. Can someone tell what approach can be used? For who don't know/use django images should explain it well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Builder</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<style>
body{width:90vw;
display:flex;
flex-direction: column;
justify-items: space-between;
align-items: center;
}
.form-choice__dropdown{
display: flex;
justify-items: space-between;
}
</style>
<div class="form__heading">
<h1 class="heading-main">
<input type="text" placeholder="Enter form heading...">
</h1>
</div>
<div class="form-choice__dropdown">
<div class="form-type1">
<label for="form-type1__select">
<select name="form-type1__select" id="">
<option value="Project Request">Project Request</option>
<option value="ToT Request">ToT Request</option>
<option value="NDA Request">NDA Request</option>
<option value="MoU Request">MoU Request</option>
<option value="Tech Service Request">Tech Service Request</option>
</select>
</label>
</div>
<div class="form-type2">
<label for="form-type2__select">
<select name="form-type1__select" id="">
<option value="National">National</option>
<option value="International">International</option>
</select>
</label>
</div>
<div class="form-type3">
<label for="form-type1__select">
<select name="form-type1__select" id="">
<option value="Sponsored">Sponsored</option>
<option value="Collaborative">Collaborative</option>
<option value="Consultancy">Consultancy</option>
</select>
</label>
</div>
</div>
<div id="question-answer-pairs" class="question-answer-pairs">
<button id="add-question">Add Question</button>
</div>
<script>
window.removeQuestion = function (el) {
el.parentNode.parentNode.removeChild(el.parentNode);
}
const putRadioOptions = function () {
this.insertAdjacentElement("afterbegin",
`<input type='text' placeholder="Enter comma separated options(Do not use comma in any option) ">`
)
}
var questionNumber = 1;
var questionList
document.getElementById("add-question").addEventListener('click', function (event) {
let addQuestionButton = event.currentTarget;
let questionAnswerPair = `
<fieldset>
<legend class="question${questionNumber}__question">
Put in the Question${questionNumber}
<input type="text" >
</legend>
<label for="answer${questionNumber}-type">
Choose type of answer field:
<select name="answer${questionNumber}-type" class="question${questionNumber}__answer">
<option value="email">Email </option>
<option value="tel">Telephone</option>
<option value="file">File Upload</option>
<option value="radio" onclick="putRadioOptions()">Radio Buttons</option>
<option value="sex">Sex</option>
<option value="url">Range</option>
<option value="date">Date</option>
</select>
</label>
<button onclick="removeQuestion(this)">Remove</button>
</fieldset>
`
addQuestionButton.insertAdjacentHTML("beforebegin", questionAnswerPair);
++questionNumber;
}
)
</script>
</body>
</html>
This is it
After removing Question2
I don't just need to change the text, that's easy. The problem is that the name= question${questionNumber} should too change to 2 when I remove the 2nd question for question number 3. So I want to see this with numbers in all those classes and names and ids automatically numbered consecutively.
enter image description here
javascript python django
Using the principles of event delegation I added an eventListener to the div with id="question-answer-pairs". Now iterating through all the fieldsets and replacing all numbers with the for loop index variable with regex is what I did.
The regex is bad but works good in my case. For people using h1 tag or other tags with numbers a better regex is needed.
document.getElementById("question-answer-pairs").addEventListener('click', function (event) {
if (event.target.textContent == "Remove") {
event.target.parentNode.remove();
let allFieldset = event.currentTarget.getElementsByTagName("fieldset")
for (let i = 0; i < allFieldset.length; i++) {
allFieldset[i].innerHTML = allFieldset[i].innerHTML.replace(/(.*?)(\d+)(.*)/g, `$1${i + 1}$3`);
}
questionNumber = allFieldset.length + 1;
}
})

Display selected items in a list

How to display selected items in a list?
So that the elements selected in the selector are displayed in the list below it.
Example code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>
What should be the result:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>
You need check your selected is exist or not and create it.
if( document.getElementById("mySelect") != undefined) {
document.getElementById("mySelect").remove();
}
var selectList = document.createElement("select");
And you map function to create options selected in change event handle as
function change (options) {
var parent = document.getElementsByClassName("md-form")[0];
if( document.getElementById("mySelect") != undefined) document.getElementById("mySelect").remove();
var selectList = document.createElement("select");
let selected = [...options].filter(o => o.selected).map(o => {
selectList.id = "mySelect";
selectList.multiple = "multiple";
parent.appendChild(selectList);
var option = document.createElement("option");
option.value = o.value;
option.text = o.text;
selectList.appendChild(option);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required onchange="change(this.options);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>
Another approach is to do something like that (added notes inside the code):
const userSelection = document.querySelector('[name="users"]'); // select element
const userSelect = document.querySelector('ul'); // list container
userSelection.addEventListener('change', function() { // add event listener to change of the select
const options = userSelection.querySelectorAll('option'); // list of options
options.forEach(option => { // iterate them
if(option.selected == true) { // if one of them selected
const newLI = document.createElement('li'); // create li element
newLI.textContent = option.value; // add the value of selected option as text content
newLI.addEventListener('click', function() { userSelect.removeChild(this); }); // BONUS: remove list item with click
userSelect.appendChild(newLI); // append the new created li element to the list
}
});
});
<div class="md-form">
<select name="users" multiple="multiple" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<ul></ul>
Hope that helps!
I was thinking that you could use JavaScript (JS) as a way to get the items that are selected and paste them elsewhere (wherever you want).
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select id="select" name="users" multiple="multiple"
required>
<option class="option" value="1">1</option>
<option class="option" value="2">2</option>
<option class="option" value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>
Then add JS:
// Get the select input
document.getElementByID("select")
// Get the options
document.getElementByClassName("option")
// Get the options that are selected
var print = `.option:[active]`;
// Print (paste) the selected options elsewhere on the page
if print {
document.write(print);
}
Please tell me if this works, as it might not. After all, I'm just an 8-year old, and just starting to learning web development.
You could use the following:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<script>
// References to elements
var select = document.querySelector('select'),
options = Array.from(select.querySelectorAll('option')),
form = document.querySelector('.md-form'),
ul = document.createElement('ul');
// Variables with information
var selected = [];
select.addEventListener('change', function() {
selected = [];
ul.innerHTML = '';
options.map(function(el) {
if (el.selected) selected.push(el);
});
if (selected.length) {
selected.map(function(el) {
var li = document.createElement('li');
li.textContent = el.textContent;
ul.appendChild(li);
});
form.appendChild(ul);
} else {
form.removeChild(ul);
}
});
</script>
</body>
</html>
Working fiddle:
https://jsfiddle.net/1j7a9h35/

Hide all but 1 dif on document ready and unhide divs after "change"

I am creating a business options form (rough description I know, but here goes). I want the first select that pops up to be to choose an Entity Type (IE: Corporation, LLC, LLP, etc). Once one of these is chosen, I want to .show() the next form. Here is what I've tried so far:
HTML FILE
<head>
<link rel="stylesheet" type="text/css" href="hide.css">
<script src="//code.jquery.com/jquery-1.10.2.js">
function getEntityType(sel) {
var openingEntityType = sel.value;
$("#basicOpeningEntityInformation").show();
}
</script>
</head>
<body>
<select id="oet" onchange="getEntityType(this)">
<option value="">Select an Option</option>
<option value="inc">Corporation</option>
<option value="llc">Limited Liability Company</option>
<option value="llp">Limited Liability Partnership</option>
<option value="lp">Limited Partnership</option>
<option value="gp">General Partnership</option>
<option value="jv">Joint Venture</option>
<option value="dba">Sole Proprietorship</option>
</select>
<br/>
<br/>
<form id="basicOpeningEntityInformation">
Entity Name:
<input type="text" id="openingEntityName">
<br/>
</form>
</body>
CSS FILE:
#basicOpeningEntityInformation {
display: none;
}
When the page loads, #basicOpeningEntityInformation is hidden. I want it to be unhide when a select from above is chosen. I tested my console and the select is passing it's value to var openingEntityType as it should; however, it is not making the other form visible. I tired with both .basicOpeningEntityInformation and #basicOpeningEntityInformation and neither seem to work (both in the CSS and the Script.
Thank you!
You need to check if the selected value is one of the required values:
$('#oet').on('change', function() {
var selectedItem = $(this).val();
if (selectedItem == 'inc' || selectedItem == 'llc' || selectedItem == 'llp') {
$('#basicOpeningEntityInformation').show();
} else {
$('#basicOpeningEntityInformation').hide();
}
});
Demo: https://jsfiddle.net/tusharj/L4b0wpts/1/
Try adding this..it will work
<head>
<link rel="stylesheet" type="text/css" href="hide.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"> </script>
<script>
function getEntityType(sel) {
var openingEntityType = sel.value;
jQuery("#basicOpeningEntityInformation").show();
}
</script>
</head>
you are using $(".basicOpeningEntityInformation").show();
so change the
id="basicOpeningEntityInformation" to class="basicOpeningEntityInformation"
OR
$(".basicOpeningEntityInformation").show(); to $("#basicOpeningEntityInformation").show();

Categories

Resources