How to elegantly add and remove elements from DOM - javascript

So I have a dynamic form where certain inputs should only become available (and visible) based upon what a user has already entered. The way I'm starting to go about it has a wrong smell.
It is straightforward enough to add material to the DOM
<script>
function addStuffToTheDOM(s1, s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value==="job_1"){
s2.insertAdjacentHTML('afterend', '<p><select name="scholarship" id="scholarship"><option value="" disabled="disabled" selected="selected">*Position</option> <option value="" disabled="disabled" > </option> <option value="HR">HR</option> <option value="CTO">CTO</option> <option value="test">test</option> <option value="test2">test2</option> <option value="test3">test3</option> <option value="test4">test4</option> </select> </p> <select name="previous_experience" class="hidden"
id="new_to_demo"><option value="0" disabled="disabled" selected="selected"></option> <p> <p> <input type="text" name="supervisor" id="supervisor" maxlength="50" size="30"> <label for="supervisor">*Supervisor</label> </p> <p> <input type="text" name="office_location" id="office_location" maxlength="50" size="30"> <label for="office_location">Office location</label> </p> <p> <input type="text" name="programme_start_date" id="programme_start_date" maxlength="50" size="30"> <label for="programme_start_date">programme_start_date</label> </p>');
}
}
</script>
<!-- .... -->
<form>
<!-- ... -->
<select name="type" id="type" onchange="addStuffToTheDOM(this.id, 'alma_mater')">
<option value="" disabled="disabled" selected="selected">*Job Interest?</option>
<option value="" disabled="disabled" > </option>
<option value="job_1">The really big job</option>
<option value="job_2">The other job</option>
</select>
And while this insertion in itself could be better (instead of jamming an enormous string into insertAdjacentHTML() ) an immediate problem presents itself in that
If the user has made a mistake and selects the other option (for which all that inserted HTML is irrelevant) then some other code will have to be run to remove all those new elements. Yuck.
Without this removal process if the user selects the other option and then goes back and selects option "job_1" again, then the form is immediately broken by the duplication of all that content. Yikes.
The backend checking has to be extra careful to do proper checking: are inputs empty because they haven't been filled in, or because they simply don't exist?
What would be the ideal methodology for implementing this dynamic content?

Yes, that has a worrying smell. You could create a check-function that runs each time someone clicks/types (depending on what you want to include in your form) a field. That functions itself needs certain conditions that are going to be checked.
This is a quick example I put together. Use jQuery (or regular javascript if you want) and put together something like this. Hope this helps!
$(document).ready(function(){
$('#checkbox').click(function(){
if($("#checkbox").is(':checked'))
$("#textbox").hide();
else
$("#textbox").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<input id="checkbox" type="checkbox">I want to hide a textbox</input><br>
<input id="textbox" type="textbox" placeholder="This can be hidden"></input>
</form>
EDIT: To add, if you want to check for textbox values or textareas, in jQuery you use for example:
$('#textbox').val();

Related

how can I use JS to Remove a tag off when a Option is selected in a HTML form?

I'm creating an artist's site. There is a contact form on the site, and I am trying to create a JS script to remove the hidden class I put on the commission rules, so it can be visible when the Commission option is selected on the form. I'm new to JS, but From the documentation I've read HTMLOptionElement type seems to be the best way to do this in vanilla JS. Here is the form, and my approximations of trying to remove the element:
<form action="action_page.php" id="contactform" method="post" action="FormToEmail.php">
<input name="name" type="text" class="feedback-input" placeholder="Name" />
<input name="email" type="text" class="feedback-input" placeholder="Email" />
<select id="reason" name="contact-reason">
<option value="None" selected disabled hidden>Reason for contact</option>
<option value="Brand">Brand</option>
<option id="Comission"value="Comission">Commission</option>
<option value="Other">Other</option>
</select>
<a class="invis hidden center" href=""> Commission rules</a>
<textarea name="contact-message" class="feedback-input" placeholder="Comment"> </textarea>
<input type="submit" class="button form-buttion" value="SUBMIT"/>
</form>
I've also tried selecting by ID, by tags, and other selectors. The JS is here.
var action = document.HTMLOptionElement("Commission")
if(action == true){
element.classList.remove("invis");
}
document.HTMLOptionElement is not a function. The correct way to check if an option is selected is:
document.getElementById('reason').value === "Commision";
You can also remove the id from the option element.
So:
if(document.getElementById('reason').value === "Commision"){
element.classList.remove("invis");
}

ASP .NET Core MVC - Post List data from HTML select control into MVC Controller

I am working on a form for my site of which users can input their account names and then they submit the list of account names.
Below is my HTML of which is inside a form (Please ignore any smelly code, I will sort it).
<div class="form-group">
<label asp-for="Accounts" class="control-label site-font">Accounts<b style="color: red">*</b></label>
<select id="account-list" name="accounts[]" multiple="multiple" class="form-control" asp-for="Accounts"></select>
<div style="margin-top: 1%"></div>
<input type="text" id="account-name" placeholder="Enter your Account Name" class="form-control" asp-for="Accounts" />
<div style="margin-top: 1%"></div>
<select id="platform-list" class="form-control">
<option>Xbox</option>
<option>PS4</option>
<option>PC</option>
</select>
<div style="margin-top: 1%"></div>
<select id="software-list" class="form-control">
<option>Microsoft Account</option>
<option>Playstation Network</option>
<option>Uplay</option>
<option>Steam</option>
<option>Discord</option>
<option>None of the above</option>
</select>
<div style="margin-top: 1%"></div>
<input type="checkbox" id="main-account"/> Main Account
<div style="margin-top: 1%"></div>
<input type="button" class="submit-button" value="Add Account" id="add" />
<span id="account-error" asp-validation-for="Accounts" class="text-danger"></span>
</div>
My issue is that whenever I click submit I get an Invalid Cast Exception.
My Controller takes a type of Member of which the Accounts property is a list of string.
Below is what the user will see when they have added a few of their accounts, and each row will be an item within the list.
I have used JavaScript to get this working, but I don't think that this will have any effect on the issue, so I haven't included it in the question but if you want to see it then let me know.
If I have missed anything, or the question is unclear then please let me know and I will try to get back to it as soon as possible.
The reason you're getting the error is because the form is posted with something as follows:
"accounts[]" = "SelectedOption1"
"accounts[]" = "SelectedOption2"
"accounts[]" = "SelectedOption3"
....
I think that the easiest way to get around this would be to make the "Accounts" property an array/list of strings. If you are unable to do that you could use JS to store the selected values in a comma-delimited string and post that field to the accounts property instead of the control:
<select id="account-list" multiple="multiple" class="form-control" asp-for="Accounts">
<option>Test</option>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
<input type="hidden" id="accountInternal" name="accounts[]" value="" />
$("form").submit(function () {
$("#accountInternal").val($("#account-list").val().toString());
return true;
});

How to auto Set input values in a form when select an option?

I have a form for example:
<form>
<ul>
<li>
<select name="choose">
<option value="0">1</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li><h2>No. Of person</h2></li>
<input type="text" name="ref_person"id="field" value="" />
<li><h2>earning of person:</h2></li>
<input type="text" name="ear_person" id="field" value="" />
</ul>
</form>
so, when I choose option:1 both the input fields must be filled with no. let say, No. of person = 3 and earning of person = $5.
Your question should be as well written as you can make it, including valid, semantic HTML.
Also, a question should contain the code you have tried, an explanation of what you have tried, where it's going wrong and exactly what you expect it to do, including some example input and output.
The following may help. Note that element IDs must be unique and that forms should use semantic markup (e.g. don't use a list to present it, don't put headings inside lists, use labels, group elements using fieldsets, etc.).
You can use the select element's change event to get the value and text of the selected option and display it elsewhere in the form. You can also reference form controls as named properties of the form, which is handy and more straight forward than using getElementById.
In the code, a reference to the select is passed to the function using this. Every form control has a form property that is a reference to the form that it's in. The rest should be easy enough to understand, but please ask if you need other help.
function getPerson(select) {
var form = select.form;
form.ref_person.value = select.options[select.selectedIndex].text;
form.ear_person.value = select.value;
}
<form>
<fieldset><legend>Person and earning</legend>
<label for="personSelect">Select a person
<select name="choose" id="personSelect" onchange="getPerson(this)">
<option value="0">1</option>
<option value="100">2</option>
<option value="500">3</option>
</select>
</label>
<br>
<label for="personNumber">No. Of person:
<input type="text" name="ref_person"id="personNumber"></label>
<label for="personEarning">Earning of person:
<input type="text" name="ear_person" id="personEarning"></label>
</fieldset>
</form>
function getPerson(select) {
var form = select.form;
form.ref_person.value = select.options[select.selectedIndex].getAttribute('per');
form.ear_person.value = select.value;
}
<form>
<fieldset><legend>Person and earning</legend>
<label for="personSelect">Select a person
<select name="choose" id="personSelect" onchange="getPerson(this)">
<option per="3" value="0">1</option>
<option per="9" value="100">2</option>
<option per="27" value="500">3</option>
</select>
</label>
<br>
<label for="personNumber">No. Of person:
<input type="text" name="ref_person"id="personNumber"></label>
<label for="personEarning">Earning of person:
<input type="text" name="ear_person" id="personEarning"></label>
</fieldset>
</form>
Here is a code sample that uses the onchange event to copy values to the textboxes.
<script type="text/javascript">
function selectOnChange(obj) {
var val = obj.options[obj.selectedIndex].value;
var text = obj.options[obj.selectedIndex].text;
document.getElementById("field1").value = val;
document.getElementById("field2").value = text;
}
</script>
</head>
<body>
<div>
<select onchange='selectOnChange(this)' name="choose">
<option value="100">1</option>
<option value="200">2</option>
<option value="300">3</option>
</select>
</div>
<ul><li><h2>No. Of person</h2></li></ul>
<div>
<input type="text" name="ref_person" id="field1" value="">
<ul>
<li><h2>earning of person:</h2></li></ul>
<input type="text" name="ear_person" id="field2" value="" />
</div>
I couldn't get a switch statement to work, so I did it with three if statements, but here is my solution. Fiddle with it yourself to make it as you wish.
<form>
<ul>
<li>
<select name="choose" id="option1" onchange="relatedPrice()">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select>
</li>
<li><h2>No. Of person</h2></li>
<input type="text" name="ref_person" id="field1" value="" />
<li><h2>earning of person:</h2></li>
<input type="text" name="ear_person" id="field2" value="" />
</ul>
</form>
<script>
function relatedPrice() {
var e = document.getElementById("option1");
var test = e.options[e.selectedIndex].text;
document.getElementById("field1").value = test;
if(test==1) {
document.getElementById("field2").value = 100;
}
if(test==2) {
document.getElementById("field2").value = 200;
}
if(test==3) {
document.getElementById("field2").value = 300;
}
}
</script>

javascript form option value split into two different input values

Okay so I have been trying to figure this out but do not have the knowledge to proceed.
I have a form with select options. The options will have two values, input-value="value1/value2".
I have a script started that pulls out the value and creates an array. I need ti figure out how to separate the two values and print out into two separate input values.
<html>
<body>
<p>The Thank you page is <b id='brochure'>is what?</b> </p>
<p>This should print out the selected fid <script>document.getElementById('brochure').innerHTML = '<input id="" value="'+option_array[1]+'" />';</script></p>
<form>
Activity Level: <select id="activity_level">
<option value="null">Please Choose One...</option>
<option id="brochure" value="brochure/print">fid/sid</option>
<option id="online" value="online/web">Three/Four</option>
<option id="inPerson" value="inPerson">Five/Six</option>
</select></br>
<input type='button' onclick='brochure_select()' value='Change Text'/>
<script type="text/javascript">
function brochure_select() {
var option_result = document.getElementById("activity_level").value;
var option_array=option_result.split("/");
document.getElementById('brochure').innerHTML = option_array[1];
}
</script>
// below is where I want to two value to show up.
<input type="hidden" name="fid" value="brochure" />
<input type="hidden" name="sid" value="print" />
</form>
</body>
</html>
I have tried the split function but I am not sure how to get it into the different input values.
Any ideas that I can research or code examples someone might have to share. I have gone through many different searches and have not found what I am looking for...
Thanks
Tim
What you need is an id attribute for your hidden input elements, and to use the value property instead of innerHTML.
<form>
Activity Level:
<select id="activity_level">
<option value="null">Please Choose One...</option>
<option id="brochure" value="brochure/print">fid/sid</option>
<option id="online" value="online/web">Three/Four</option>
<option id="inPerson" value="inPerson">Five/Six</option>
</select><br />
<input type='button' onclick='brochure_select()' value='Change Text'/>
</form>
<input type="hidden" id="fid" name="fid" value="" />
<input type="hidden" id="sid" name="sid" value="" />
<script>
function brochure_select() {
var option_result = document.getElementById("activity_level").value;
var option_array=option_result.split("/");
document.getElementById('fid').value = option_array[0];
document.getElementById('sid').value = option_array[1];
}
</script>

Show (Visible/Hidden NOT Show/Hide) HTML Element based on form select box selection

The following worked perfectly for my needs. Took the state of a checkbox and did wonderful things for me; Made 3 different form elements visible (vs. show/hide) based on checkbox checked or not checked. Simple, I guess. Then again, I base "simple" on how symmetrical the code looks and if it's less that 10 lines. Other than that, I'm lost. However, I've officially given up on messing around with IE's checkbox border issue and X-browser alignment yippeedoodles. I want pixel perfect the hard way. But I lost that battle. But rather than get into any discussion about that, I need to accomplish the same thing using a form select box as I was able to do with the checkboxes (below):
<form id="form">
<input id="checkbox" name="checkbox" type="checkbox" onclick="showhideid" />
</form>
#IdOne, #IdTwo, #IdThree (visibility:hidden;}
function showhideid()
{
if (document.form.checkbox.checked)
{
document.getElementById("IdOne").style.visibility = "visible";
document.getElementById("IdTwo").style.visibility = "visible";
document.getElementById("IdThree").style.visibility = "visible";
document.getElementById("IdFour").setAttribute("class", "required");
}
else
{
document.getElementById("IdOne").style.visibility = "hidden";
document.getElementById("IdTwo").style.visibility = "hidden";
document.getElementById("IdThree").style.visibility = "hidden";
document.getElementById("IdFour").setAttribute("class", "");
}
}
Now, if I can accomplish the same thing using a select box (below), I will die a happy man.
This is as far as I've gotten. I'm super dizzy from reading Jquery/CSS man pages and I just can't put it all together.
<html>
<form id="form">
<select name="SelectBox">
<option>Make a Choice</option>
<option value="Value1">Selection1</option>
<option value="Value2">Selection2</option>
<option value="Value3">Selection3</option>
</select>
<label id="IdOne" for="input1">MeAndMyInputAreInvisibleByDesign</label>
<input id="IdTwo" name="input1" type="text">
<span id="IdThree">Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="I have none, but I will soon. I hope" />
</form>
</html>
take a look at the select tag:
<select name="SelectBox">
<option>Make a Choice</option>
<option value="IdTwo">Selection1</option> <!-- the value should be the id of the input field -->
<option value="IdThree">Selection2</option>
<option value="IdFour">Selection3</option>
</select>
Now you must give a selector class to each element you want to show/hide:
<input id="IdTwo" name="input1" type="text" class="toggle">
<span id="IdThree" class="toggle">
Im Not In display:none Mode I'm In visibility:hidden Mode. Big difference."
</span>
<input id="IdFour" name="input2" type="text" class="toggle" />
Now look at the javascript:
jQuery(document).ready(function(){
jQuery('input[name="SelectBox"]').change(function(){
jQuery('.toggle').css({"visibility":"hidden"});//Hide all
jQuery("#" + jQuery(this).val()).css({"visibility":"visible"});
});
});
You can do something like this:
<html>
<form id="form">
<input type="text" id="IdOne" class="toggle" />
<input type="text" id="IdTwo" class="toggle" />
<input type="text" id="IdThree" class="toggle" />
<select name="SelectBox" id="selectBox">
<option value="0">Make a Choice</option>
<option value="IdOne">First element</option>
<option value="IdTwo">Second element</option>
<option value="IdThree">Third element</option>
</select>
</html>
this in javascript:
jQuery(document).ready(function(){
jQuery("#selectBox").change(function(){
jQuery(".toggle").hide();
jQuery("#" + jQuery(this).val()).show();
});
});

Categories

Resources