Selected Text in new line with drop down menu - javascript

I want to make some drop down menu and get the code from here:
How to fill in a text field with drop down selection
http://jsfiddle.net/kjy112/kchRh/
HTML:
<textarea id="mytext"></textarea>
<select id="dropdown">
<option value="">None</option>
<option value="text1">text1</option>
<option value="text2">text2</option>
<option value="text3">text3</option>
<option value="text4">text4</option>
</select>
JavaScript:
<script type="text/javascript">
var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + this.value; //to appened
//mytextbox.innerHTML = this.value;
}
</script>
But I want the new text after another have to be inserted into new line of text area, none the same line with previous selected option.
Any help is appreciated. Thank everyone.

Please Look Into The JS Fiddle
http://jsfiddle.net/s293s7cz/
mydropdown.onchange = function(){
if(!mytextbox.value)
mytextbox.value = this.value; //first case or else you will have a newline at first
else
mytextbox.value = mytextbox.value + '\n' + this.value;
}

Try in such a way also.
mytextbox.value = mytextbox.value + this.value +"\n";

You can put a "\r\n" to insert the new line
mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + "\r\n" + this.value;
}
You have just to verify the first item to not insert a new line até first place

You have to explicitly add the new line:
mytextbox.value = mytextbox.value + "\n" + this.value;
If you don't want a blank line to be added upon adding the first entry to the textarea then code for that:
if(mytextbox.value) {
mytextbox.value = mytextbox.value + "\n" + this.value;
} else {
mytextbox.value = this.value;
}

Related

jQuery .val() doesnt return the value of an option tag

I have some JavaScript-generated html code. The JavaScript generates the elements (option) in a drop down list (select). I then want to get the value of the selected option '1', however instead 'test' is returned.
The html is generated using:
var newSelect = document.createElement('option');
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
I have then tried the following methods to get the value of the selected option:
var siteId = $('#siteID').val(); // returns 'test'
var siteId2 = $('#siteID').data("value"); // returns undefined
var siteId3 = $('#siteID').attr("value"); // returns undefined
var siteId4 = $('#siteID').prop("value"); // returns 'test'
You are using a very strange way to create your option - you create an option and then insert an option string as innerHTML
Fixed code (see example later)
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
Also you do not actually select the option, so the value will be whatever the browser thinks is selected
Why not use jQuery?
$("<option />", { value: 1, text: "test" }).appendTo('#siteID1')
$('#siteID1').prop("selectedIndex", 1); // NOW the value is 1
console.log(
$('#siteID1').val()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID1">
<option value="">Please select</option>
</select>
Your code:
var test ="Test";
var newSelect = document.createElement('option'),
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
console.log(document.getElementById('siteID').outerHTML)
<select id="siteID">
</select>
Your FIXED code
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
console.log(document.getElementById('siteID').value, $('#siteID').val())
console.log(document.getElementById('siteID').outerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID">
</select>
You created the option newSelect then you try to insert an option inside of it with innerHTML which is where you went wrong.
This is what you should have done.
var newSelect = document.createElement('option');
newSelect.innerHTML = 'test';
newSelect.value= '1';
document.getElementById('siteID').add(newSelect);
You need remove //selectHTML = "<option value=" + 1 + ">" + test + "</option>";
And change to newSelect.value = 1; for add value to option by javascript
newSelect.innerHTML = test;
newSelect.value = 1;
var newSelect = document.createElement('option');
var test = 'test';
//selectHTML = "<option value=" + 1 + ">" + test + "</option>";
newSelect.innerHTML = test;
newSelect.value = 1;
document.getElementById('siteID').appendChild(newSelect);
$(document).ready(function(){
var siteId = $('#siteID').val(); // r
console.log(siteId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='siteID'>
</select>
Please try this
var test = 'test';
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
$("#siteID").append(selectHTML);
var siteId = $('#siteID').val();
console.log(siteId);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID"></select>
You can first create the Select tag and after that try to append the option tag. I have attached the code as below:
// create the select tag and append with the main div tag
var string = '<select id="dropdown_tag"></select>';
$("#test").append(string);
// create as many option you want and append with the select tag
var newSelect = document.createElement('option');
selectHTML = "<option>---select---</option>";
selectHTML += "<option value='1'>1</option>";
selectHTML += "<option value='2'>2</option>";
$("#dropdown_tag").append(selectHTML);
// Onchange event of dropdown tag
$(document).on('change',"#dropdown_tag", function()
{
alert($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Dropdowm:<div id='test'></div>

How to run multiple functions from a select element using javascript

I am trying to write a simple tool for some folks in my workplace. I am trying to run different functions depending on option values picked from a html select element. And I am stuck... please dont laugh.Just got back into coding 3 weeks ago.how i want this to work is the user clicks to lower dropdown menu... selects an option... then is asked for adding additional input, then that with some predefined text is added to a text area.then then the menu resets. Please make answers as simple as possible.
<!-- BEGIN ROUTING DROPDOWN MENU -->
<select id="routingdropdownmenu">
<option value="">MAKE A SELECTION</option>
<option value="1">ROUTE TO STORE</option>
<option value="2">ROUTE TO WAREHOUSE...</option>
<option value="2">CANCEL SHIPPING</option>
<script>
var mytextbox = document.getElementById('REMARKSTEXTAREA');
var mydropdown = document.getElementById('routingdropdownmenu');
mydropdown.onclick = function(){
var INVOICE = prompt("WHAT IS THE INVOICE NUMBER?");
if (INVOICE != null) {
if (mydropdown = 1) {
mytextbox.value = mytextbox.value + " ROUTING INVOICE " + INVOICE + " TO STORE ";}
else
if (mydropdown = 2) {
mytextbox.value = mytextbox.value + " ROUTING INVOICE " + INVOICE + " TO WAREHOUSE ";}
else
if (mydropdown = 3) {
mytextbox.value = mytextbox.value + "CANCELLING SHIPMENT";}
this.value = "";
</script>
</select>
<!-- END ROUTING DROPDOWN MENU -->
Did you lost your element whose id is REMARKSTEXTAREA
You need bind a onchange function not onclick
You need to use mydropdown.value to get selected values
You need to use == not = to do the switches .
Html
<input id="REMARKSTEXTAREA" />
<select id="routingdropdownmenu">
<option value="">MAKE A SELECTION</option>
<option value="1">ROUTE TO STORE</option>
<option value="2">ROUTE TO WAREHOUSE...</option>
<option value="3">CANCEL SHIPPING</option>
</select>
javascript
var mytextbox = document.getElementById('REMARKSTEXTAREA');
var mydropdown = document.getElementById('routingdropdownmenu');
mydropdown.onchange = function(){
var INVOICE = prompt("WHAT IS THE INVOICE NUMBER?");
if (INVOICE != null) {
if (mydropdown.value == 1) {
mytextbox.value = mytextbox.value + " ROUTING INVOICE " + INVOICE + " TO STORE ";
}
else if (mydropdown.value == 2) {
mytextbox.value = mytextbox.value + " ROUTING INVOICE " + INVOICE + " TO WAREHOUSE ";
}
else if (mydropdown.value == 3) {
mytextbox.value = mytextbox.value + "CANCELLING SHIPMENT";
}
}
}
How useful would this really be in a real work environment if you don't know enough to do this part?
Anyways, the change event will trigger the select's event handler. Event handler will only accept an input in the text input and will prompt for one until one is entered or cancel button is clicked in which case it quits all together.
Using a switch and the selectedIndex of the select determines what is printed in the output element.
SNIPPET
var text = document.getElementById('invNum');
var menu = document.getElementById('routeMenu');
menu.addEventListener('change', function(e) {
var INVOICE = text.value;
while (INVOICE == 'undefined' || INVOICE == '' || INVOICE == null) {
if (INVOICE == null) {
return false;
} else {
INVOICE = prompt("Enter Invoice Number First");
}
}
var out = document.getElementById('out');
var opt = menu.selectedIndex;
switch (opt) {
case 1:
out.textContent = " ROUTING INVOICE " + INVOICE + " TO STORE ";
break;
case 2:
out.textContent = " ROUTING INVOICE " + INVOICE + " TO WAREHOUSE ";
break;
case 3:
out.textContent = "CANCELLING SHIPMENT";
default:
return false;
}
}, false);
<fieldset>
<legend>Route Menu</legend>
<label>Invoice Number
<input id='invNum'>
</label>
<select id="routeMenu">
<option value="">Select Option</option>
<option value="1">Route to Store</option>
<option value="2">Route to Wharehouse</option>
<option value="3">Cancel Shipping</option>
</select>
<br/>
<br/>
<output id='out'></output>
</fieldset>

jQuery: accessing (multi) .attr()

I have a problem accessing the information of a (multi) .attr(...)
I found this and tried to adapt it - but it does not work. I am missing something obvious here (new to js). Hope to find help here!
var user_id = document.getElementById('myselect').options[select.selectedIndex].user_id;
var user_email = document.getElementById('myselect').options[select.selectedIndex].user_email;
document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;
<select id="myselect">
<option user_email="test#test.de" user_id=1>Test 0</option>
<option user_email="email#email.de" user_id=1>Test 1</option>
<option user_email="whyso#serious.de" user_id=1>Test 3</option>
</select>
<div id="display"></div>
Try this:
var index = document.getElementById('myselect').selectedIndex;
var user_id = document.getElementById('myselect').options[index].getAttribute('user_id');
var user_email = document.getElementById('myselect').options[index].getAttribute('user_email');
document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;
select.selectedIndex doesn't exist in your example. This should work:
var select = document.getElementById('myselect');
var user_id = select.options[select.selectedIndex].getAttribute('user_id');
var user_email = select.options[select.selectedIndex].getAttribute('user_email');
document.getElementById('display').innerHTML = 'User with ID' + user_id + " has email address " + user_email;

JQuery autocomplete works for one section but not the other

I'm trying to get a JQuery function to pick up specific changes to a form and then plug the information into equations so that each section of the form has answers created for it automatically. I got the first part of it to work (Quantity for Posts) but can't get the second part to work (Quantity for Rails). If anyone can point out or explain where I went wrong and how I could fix it it would be greatly appreciated! Thanks!
Here is a JSFiddle - http://jsfiddle.net/gv0029/ncn42/1/
HTML:
<fieldset id="fence">
<div name="inputFence" class="inputFence">
<legend><strong>Fence Description</strong>
</legend>
<label>Footage:
<input name="footage_1" class="footage" />
</label>
<select name="fenceHeight_1" class="fenceHeight">
<option value="select">Select Fence Height</option>
<option value="6" id="fH6">6 Ft.</option>
<option value="8" id="fH8">8 Ft.</option>
</select>
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input name="postQuantity_1" class="postQuantity" />
</label>
<legend><strong>Rail Type</strong>
</legend>
<select name="6foc_1" class="6foc">
<option value="select">6 Ft. on Center?</option>
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<label>Quantity:
<input class="railQuantity" name="railQuantity_1" />
</label>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS:
//Quantity for Posts
$(document.body).on('keypress keydown keyup change', '[class^="footage"] ', function () {
var footage = parseFloat($(this).val(), 10);
var total = '';
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
if (!isNaN(footage)) {
total = Math.ceil(footage / 7);
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val(total.toString());
} else {
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val("");
}
});
//Quantity for Rails
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]', function () {
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
var footage = parseFloat($(":input[name='footage_" + fenceNumber + "'" + ']').val(), 10);
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
var total = '';
var sfoc = $(":input[name='6foc_" + fenceNumber + "'" + ']').val();
if (fenceHeight = !NaN) {
if (sfoc == "no") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 8) * 4);
}
if (fenceHeight == '6') {
total = (Math.ceil(footage / 8) * 3);
}
railQuantity.val(total);
}
if (sfoc == "yes") {
if (fenceHeight == '8') {
total = (Math.ceil(footage / 12) * 4);
railQuantity.val(total);
}
if (fenceHeight == '6') {
alert("Error: 6ft on Center cannot use 6ft posts");
railQuantity.val("ERROR");
}
}
} else {
railQuantity.val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
parts = $('.6foc:last').attr('name').split("_");
parts[1]++;
$('.6foc:last').attr('name', parts.join("_"));
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
You had a few problems.
First was this line:
$(document.body).on('keypress keydown keyup change', '[class^="footage"] [class^="fenceHeight"] [class^="6foc"]',
You have to separate the different inputs with a comma as shown here:
$(document.body).on('keypress keydown keyup change', '[class^="footage"],[class^="fenceHeight"],[class^="6foc"]',
Second was this line:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').val();
You're getting the value of the select, when really you want the value of the selected option:
var fenceHeight = $(":input[name='fenceHeight_" + fenceNumber + "'" + ']').find('option:selected').val();
Third was this line:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
You're getting the value of this line, when down in the code you're actually trying to set the value of the value. What you want is just the element. I've left the quantity in there in case you want that later, but repurposed railQuantity:
var railQuantity = $(":input[name='railQuantity_" + fenceNumber + "'" + ']');
var railQuantityval = $(":input[name='railQuantity_" + fenceNumber + "'" + ']').val();
Fourth is your if statement:
if (fenceHeight = !NaN) {
You can't really use it like that. Use this instead:
if (!isNaN(Number(fenceHeight))) {
Down in the if statement, you also could benefit from if/else statements instead of just if statements. I've changed those to reflect this.
You were also missing the railsQuantity element in your add function, which I added for you:
parts = $('.railQuantity:last').attr('name').split("_");
parts[1]++;
$('.railQuantity:last').attr('name', parts.join("_"));
Updated fiddle here.

jQuery select option value

How do you set the "city" value to the same thing as country value when there is no option for a city?
For example, Benin doesn't have an option to select a city inside of it. At this link http://jsfiddle.net/yPb6N/1/, if you select "Benin", underneath the dropdown it displays Benin undefined. How do you make it display Benin Benin?
<select id="country-select">
<option value="us">US</option>
<option value="germany">Germany</option>
<option>Ireland</option>
<option>Benin</option>
<option>Italy</option>
</select>
<select id="us-select" class="sub-menu hide">
<option value="austin">Austin</option>
</select>
<select id="germany-select" class="sub-menu hide">
<option value="berlin">Berlin</option>
</select>
<p></p>
<font size="5"><font color="red"><div class="countryvalue" >Value</div></font></font> <br/>
​
function countrySelectChanged() {
$('.sub-menu').hide();
var selectedCountry = $('#country-select').val();
if (selectedCountry) {
$('#' + selectedCountry + '-select').show();
}
}
$(document).ready(function() {
$('#country-select').change(countrySelectChanged );
countrySelectChanged();
$("#country-select").change(function () {
var str = $('#country-select').val() + " " + $("#" + $("#country-select option:selected").val() + "-select option:selected").val();
$("#country-select option:selected").each(function () {
});
$(".countryvalue").text(str);
})
.change();
});
​
.hide {
display: none;
}​
My code is not working
if (($('#country-select').val() != "us") || ($('#country-select').val() != "germany")) {
$("#" + $("#country-select option:selected").val() + "-select option:selected").val() == $('#country-select').val();
}
thanks :-)
This line:
var str = $('#country-select').val() + " " + $("#" + $("#country-select option:selected").val() + "-select option:selected").val();
Needs to be somthing like:
var country = $('#country-select option:selected').val();
var city = $("#" + country + "-select option:selected").val() || country;
$(".countryvalue").text(country + " " +city);
This way, if the name of the city doesn't exist, it will use the name of the country. Also, it doesn't perform multiple selectors for the same element, which is wasteful.
Here is the updated fiddle.
I guess that you want to print only the country name if there is no city associated with this country. If so, I have created this fiddle : http://jsfiddle.net/scaillerie/tSgVL/1/ .
In fact, you have to test if the list associated with your country exists or not :
hasCity = $("#" + $("#country-select option:selected").val() + "-select").length !== 0
and then print or not the country.
Edit
It seems that you want to duplicate the country, so depending of the previous test, you will have :
str = $country.val() + " " + (hasCity ? $("#" + country_val + "-select option:selected").val() : $country.val());
basically what #Aesthete said, i just refactored the whole function (took some minutes), maybe you like it (i updated the fiddle: http://jsfiddle.net/yPb6N/4/):
$(document).ready(function() {
var country
, city
, $selected
, $cs = $('#country-select')
, $cv = $(".countryvalue");
$cs.on('change', function() {
country = $cs.val() || $cs.text();
$selected = $cs.find(':selected');
city = $selected.val() || $selected.text();
$('.sub-menu').addClass('hide');
if($selected.val()) {
$('#' + $selected.val() + '-select').removeClass('hide');
city = $('#' + $selected.val() + '-select').val() || country;
}
$cv.text(country + ' ' + city);
});
$cs.trigger('change');
});​

Categories