I am trying to output the HTML of all the selected options from a dropdown list in a new div. However, everytime I select a new checkbox, my container gets updated with the selected value (like its supposed to), but it also appends every previously selected value from the dropdown list. And so on, and so on. How do I output the checkboxes HTML only once?
Heres my JS code:
let emptyArr = [];
$('.dropdown-select-container').find("option:selected").each(function(){
emptyArr.push($(this).html());
});
for (i in emptyArr) {
let outputResult = "<div class='arr-item'>" + emptyArr[i] + "</div>"
$("#container").append(outputResult);
}
Because you are using jQuery's append, your #container will always append (aka add) the contents of outputResult as opposed to replacing the contents of #container. Instead, you should use the html function to empty the contents of #container and replace the contents with outputResult like so:
$("#container").html(outputResult);
Given incomplete data, we do what we can. In future, it's always easier to diagnose what you're trying to do with complete information.
However, this is all overkill. Re-reading your post, you asked why you are getting a, then aab, then aababc, when you add more checks or whatever. The simple answer is because you're appending more and more stuff into the div, but you never remove what's already there. Before you start appending, simply call empty() on that container div. See below to see what I mean.
$(".dropdown-select-container").on("change", function() {
var emptyArr = [];
// Go through the select, find all selected options.
$('.dropdown-select-container').find(":selected").each(function() {
emptyArr.push($(this).html());
});
// remove all current content.
$("#container").empty();
// go through the array line by line,
// and create a div for each.
for (var i = 0; i < emptyArr.length; i++) {
console.log(emptyArr);
var outputResult = "<div class='arr-item'>" + emptyArr[i] + "</div>"
$("#container").append(outputResult);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
<label>Selection list</label>
<select class="dropdown-select-container" multiple>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
Related
So I have a HTML webpage in Microsoft Dynamics 365 that I'm using as a Configuration Page. It allows the user to enter their information (Name, Address, City, State, Zip/Postal, and their Billing Information such as Card Name, Card Number, expiration date, etc). I use the CRM Rest Builder's WebAPI to synchronously create the record in the database once the user enters all their information and clicks the Submit button.
What I am wondering about is whenever the user clicks the D365 Solution and loads the configuration page, it needs to show all the inputted data dynamically, so the user doesn't have to re-enter inputted data on the form (i.e. each time they click the configuration page showing the HTML file, it is not blank, their data exists). However, I am configuring it in such a way that the user makes changes only to the form.
What I've tried is using CRM Rest Builder to generate JavaScript to retrieve a single record by the record's ID (32-hexadecimal). But when I add the method of retrieving into the body of the form, using the onLoad function, the user's data doesn't load for some reason. I have included the GUID of the record for reference.
Please see the code:
function retrieveRecord() {
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/new_subscriptions(67EBDC8C-CFA5-E811-A963-000D3A3ACAF8)?$select=new_name,new_state,new_zippostal, new_cardname", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var new_name = result["new_name"];
var new_state = result["new_state"];
var new_zippostal = result["new_zippostal"];
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
<body onload="retrieveRecord()">
<div class="row">
<div class="column">
Status: <input type="text" name="Name" id="new_status">
<h2>Address Information:</h2>
Name: <input type="text" name="Name" id="new_name"><br>
State: <select id="new_state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select><br>
Zip/Postal: <input type="text" name="Zip/Postal" id="new_zippostal"><br>
</div>
</div>
</body>
I have two drop down list "optionone" and "optiontwo" and I want to change the default selected value from "option value=3>3" to option value=3 selected>3 when 2 is selected from my first dropdown list ("optionone")
<script>
function myFunction() {
var mylist = document.getElementById("optionone");
var myvalue = mylist.options[mylist.selectedIndex].value
if (myvalue == 2) {
//do stuff
document.getElementById("optiontwo")
//Change <option value=3>3 to <option value=3 selected>3
}
}
</script>
My drop down list
<select name="optionone" onchange="myFunction()">
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
<select name="optiontwo">
<option value=1>1
<option value=2>2
<option value=3>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
Which I want to change to the following when 2 is select from my first drop down list (optionone)
<select name="optiontwo">
<option value=1>1
<option value=2>2
<option value=3 selected>3
<option value=4>4
<option value=5>5
<option value=6>6
</select>
I'm a bit stuck
You have a invalid markup, <option> must be closed
There is no id attribute for second select input
You can set the value attribute instead of finding the option value using index.
value should be wrapped in quote
Instead of playing with selected attribute, setting the value will make option selected.
Instead of inline-event-binding, use addEventListener
/*
function myFunction(elem) {
document.getElementById("optiontwo").value = elem.value;
}
*/
document.getElementById('optionone').addEventListener('change', function() {
document.getElementById("optiontwo").value = this.value;
});
<select name="optionone" id="optionone" onchange="myFunction(this)">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
</select>
<select name="optiontwo" id='optiontwo'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
</select>
Thanks to the above I adapted Rayon's script to update as I wanted, as follows
<script>
document.getElementById('optionone').addEventListener('change', function() {
if (this.value == 2){
document.getElementById("optiontwo").value = 3;
}
});
</script>
remove onChange="" from html
And update you code or markup like this ..
<select name="optionone" id="optionone">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
</select>
<select name="optiontwo" id='optiontwo'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
</select>
and then add this javascript code
document.getElementById('optionone').addEventListener('change',
function() {
if(this.value == 2){
document.getElementById("optiontwo").value = 3;
}
});
and your problem will solve
I created the following form and validation:
http://jsfiddle.net/baumdexterous/NNHU2/
All the items that I want to validate work fine but I'm not sure how to validate the state dropdown field.
How can I make the state field required too and get the red box to appear around the state if it is left blank?
HTML
<label>State<br>
<select name="State">
<option value="" selected="selected">Select a State/ Province</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</label>
JavaScript
function validateForm(thisform) {
if (thisform.f_name.value == "" || thisform.email.value == "" || thisform.l_name.value == "" || thisform.State.value == "" || !thisform.officialrules.checked) {
return false;
}
}
$(function () {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
$("#prod").text("true");
mob = true;
zoom = $(window).width() / 810;
$("#main").css('zoom', zoom);
$(window).resize(function () {
zoom = $(window).width() / 810;
$("#main").css('zoom', zoom);
});
}
$(".enter").click(function (event) {
personal_data = true;
for (var i = 0; i < $("input[placeholder]").length; i++) {
if ($("input[placeholder]").not("#checkbox2").eq(i).val() == "") {
$("input[placeholder]").eq(i).addClass('active_placeholder').focus();
$("#drawer").html($("input[placeholder]").eq(i).attr("placeholder"));
personal_data = false;
correct_pd();
return false;
}
}
if (!$("#checkbox2").parent().hasClass("active")) {
$("#checkbox2").parent().next().css
$("#check_box > p").eq(1).addClass('active');
$("#checkbox2").parent().addClass('bg_red');
setTimeout(function () {
$("#checkbox2").parent().removeClass('bg_red');
}, 500);
$("#drawer").html($("#checkbox2").attr("placeholder"));
personal_data = false;
correct_pd();
}
});
function correct_pd() {
if (!personal_data) {
if ($("#drawer").css("margin-top") == "-60px") {
$("#drawer").stop(true, true).css("margin-top", 0).animate({
opacity: 1
}, 250, function () {
setTimeout(function () {
$("#drawer").css("margin-top", -60);
}, 1500)
})
}
}
}
$("input[type='checkbox']").change(function (event) {
if ($(this).is(":checked")) {
$(this).parent().addClass('active');
$("#check_box > p").eq(1).removeClass('active');
} else {
$(this).parent().removeClass('active');
}
}).change();
});
add this if condition:
if($('select[name="State"]').find('option:first-child').is(':selected')){
$('select[name="State"]').addClass('active_placeholder').focus();
return false;
}
Try something like this:
$(document).ready(function(e){
$('#btn').click(function(){
if($('#state').val() == ""){
alert("error");
$('#state').css("border", "2px solid red");
}
else alert($('#state').val());
})
});
Off course, you'll need to add an id to your select statement first
if this is html5 it could be just enough to add the required attribute to the different items that are "required", without having to run the custom content
see jsfiddle: http://jsfiddle.net/Icepickle/4ke2g/
<select required="required" id="State" name="State">
<option value="" selected="selected">Select a State/ Province</option>
<option value="AL">Alabama</option>
</select>
i just replaced the css a bit, so you could see it's a functionality in html5
I have a form with three inputs, one for City, State, and Zipcode. Using javascript I need a simple way to check if the input for City contains a value. If the input does contain a value, I then need to check if State contains a value. If city contains a value, but state does not, I then need to trigger an alert box asking the user to enter a state.
This is my form code, Thanks in advance!!
<form action="home.php" method="post" name="location">
Please enter....<br /><br /><label>city:
<input type="text" name="city" size="10"/></label>
<br /><label>state:
<select id="state" name="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District Of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select></label><br />
or <br />zipcode
<input type="text" name="zipcode" size="6" /><br />
<br /><input type="submit" value="search" />
</form>`
We get the user to enter zipcode first and then auto-fill city and state. Here is the code from zipcodeapi.com/examples:
<script type="text/javascript">//<![CDATA[
$(function() {
// IMPORTANT: Fill in your client key
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
// Set city and state
container.find("input[name='city']").val(data.city);
container.find("input[name='state']").val(data.state);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
// Build url
var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
//]]>
Zip Code Distance
It will be better to use HTML5 required form field attribute. I create the jsfiddle for your.
Note that, as it stands, they will have always selected a state, since Alabama is selected by default. You can add an option with no value and a label of "Pick a state" to change this.
With that advice taken and an id "city" on your city input
var city = document.getElementById('city'),
state = document.getElementById('state'),
cityFilled = city.value !== ''
stateBlank = state.value ==='';
if(cityFilled && stateBlank){
alert("Enter a zipcode, chump");
}
Using pure js you can write the code as
var val = document.getElementById("name").value; // get value
if(val == "") { // check its value, if null
alert("please write something here"); // alert the user..
}
And do that similarly for each and every input.
You need to add the id to each element to make the JS capture the element.
I have a select tag and I want to check if a moth is selected.
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
So do this:
if (document.registration_form.Birth_Month.value === '')
{
alert('Please fill select Month!');
}
But this JavaScript for some select-s work and for some of them, does not. Obviously, when the "- Month -" is selected the it returnes "- Month -" insted of "" (empty string). What I have done wrong? What is the best way of checking the tag's selection?
Browsers didn't always have a .value property for <select> - we used to have to get the value of the <option>:
var birthMonth = document.registration_form.Birth_Month;
if (birthMonth.options[birthMonth.selectedIndex].value === '') {
// something
}
I use jQuery .val() now. I don't remember which browsers lack the select.value property, and maybe those browsers are so old that we don't need to worry about them anymore. But jQuery doesn't use select.value - it loops through each of the options to find the selected option's value.
Of course, if you know you'll always have a single blank option as the first option, just check for selectedIndex==0.
I believe integers are a better practice for option values. Anyhow, the snippet below doesn't care if your default option value is an empty string or a zero value.
var birthMonth = document.registration_form.Birth_Month;
if(birthMonth.options[birthMonth.selectedIndex].value === false){
alert('Please fill select Month!');
}
You do not need to use 'selectedIndex'
<select name="Birth_Month">
<option value="" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
if (document.getElementById('Birth_Month').value === '')
{
alert('Please fill select Month!');
}
OR
<select name="Birth_Month">
<option value="they_did_not_select_anything" SELECTED>- Month -</option>
<option value="January">January</option>
<option value="Fabruary">Fabruary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
if (document.getElementById('Birth_Month').value === 'they_did_not_select_anything')
{
alert('Please fill select Month!');
}