How to add value in textarea using JQUERY - javascript

I need help about using append in jquery. Everytime I click button right btnRight the selected option value will add in the textarea so I used append to add the value in the textarea. It is already adding a value in the textarea but the value is "undefined,". can anyone help me why I am getting a value "undefined,"?
Sample HTML Code:
<textarea name="include_field_list" cols="70" rows="5" required="required" readonly="readonly" /></textarea>
<section class="container">
<div>
<select id="leftValues" size="5" multiple="multiple">
<option value="post_id">Post ID</option>
<option value="status">Status</option>
<option value="shipper_name">Shipper Name</option>
</select>
</div>
<div>
<input type="button" id="btnLeft" value="<<" />
<input type="button" id="btnRight" value=">>" />
</div>
<div>
<select id="rightValues" size="4" multiple>
</select>
<div>
<input type="text" id="txtRight" />
</div>
</div>
SELECT, INPUT[type="text"] {
width: 160px;
box-sizing: border-box;
}
SECTION {
padding: 8px;
background-color: #f0f0f0;
overflow: auto;
}
SECTION > DIV {
float: left;
padding: 4px;
}
SECTION > DIV + DIV {
width: 40px;
text-align: center;
}
</style>
JQUERY Code:
$("#btnLeft").click(function () {
var selectedItem = $("#rightValues option:selected");
$("#leftValues").append(selectedItem);
});
$("#btnRight").click(function () {
var selectedItem = $("#leftValues option:selected");
$("#rightValues").append(selectedItem);
/***********This code has a problem************/
$value = $( "#leftValues>option:selected" ).val();
$("textarea[name=include_field_list]").append($value + ',');
/***************/
});
$("#leftValues").change(function () {
var selectedItem = $("#rightValues option:selected");
$("#txtRight").val(selectedItem.text());
});
});

there is silly mistake take place...
when user click on button the right hand side not remain selected values.
because it's move on right side... you just need to change your direction.
$value = $( "#rightValues>option:selected" ).text();
SEE DEMO
there is an other problem if user deselect any item on right side. then this value not append in textarea.. the better way to handle this use each option in right side..
SEE THIS DEMO

Second, $(textarea).append(txt) doesn't work like you think.
Instead of .append() sth to <textarea> element simply use:
var $textarea = $("textarea[name=include_field_list]"),
$oldValue = textarea.val();
$textarea($oldValue + 'new value text')
In this jsFiddle You have working solution

You can try this code..
$("textarea[name=include_field_list]").val($value + ',');
if you are appending value after existing, then get that value and pass that value in parameter too,

You have to correct ^^^^ indicated code in your code.
$value = $( "#leftValues option:selected" ).val();
^^^^
$("textarea[name=include_field_list]").val($value + ',');
^^^^^

If you call val() on a multiple-choice select list, you get an array instead of a string. So you are actually trying to append a "," to an array. Try this:
$value = $( "#leftValues>option:selected" ).val();
$("textarea[name=include_field_list]").append($value.join( ", " ) + ',');
The JSFiddle of the fix (Without CSS): http://jsfiddle.net/hyoLedxw/

Related

jquery, js. custom text color

How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change

showing one of 3 divs depending on which select is chosen [duplicate]

This question already has answers here:
jQuery select change show/hide div event
(10 answers)
Closed 8 years ago.
I have a select box with 3 option body, strength, distance. I want to use javascript / jquery to show a div depending on which of those options is selected. so far I have just got it working on a button push http://codepen.io/Irish1/pen/iwKam
html
<form>
<p>
<label for="select">
Goal Type
</label>
<select class="typeselect">
<option value=""></option>
<option value="body">
Body
</option>
<option value="strength">
Strength
</option>
<option value="distance">
Distance
</option>
</select>
<button class="toggle">push</button>
</p>
<div class="body">
<p>
<label for="body">
Body
</label>
</p>
</div>
<div class="strength">
<p>
<label for="strength">
Strength
</label>
</p>
</div>
<div class="distance">
<p>
<label for="distance">
Distance
</label>
</p>
</div>
</form>
css
.body {
display: none;
}
.strength {
display: none;
}
.distance {
display: none;
}
javascript
$('.toggle').click(function(){
$('.body').toggle();
});
Try
//dom ready handler
jQuery(function () {
//all the elements that has to be shown/hidden, it is cached for easy access later
var $targets = $('.body, .strength, .distance');
//chang handler for the select element
$('.typeselect').change(function () {
//hide previously displayed elements
$targets.hide()
//find the element with the selected option's value as class, if empty option is selected set it to an empty set
if (this.value) {
$('.' + this.value).show()
}
})
})
Demo: Fiddle
If you want to make the button handler work then
//dom ready handler
jQuery(function () {
//all the elements that has to be shown/hidden, it is cached for easy access later
var $targets = $('.body, .strength, .distance');
var $select = $('.typeselect');
//click handler for the button
$('.toggle').click(function (e) {
//prevent the default form action of the button click
e.preventDefault();
//hide previously displayed elements
$targets.hide()
//selected value
var val = $select.val();
//find the element with the selected option's value as class, if empty option is selected set it to an empty set
if (val) {
$('.' + val).show()
}
})
})
Demo: Fiddle
$('#typeselect').change(function(event) {
$('.target').hide();
var option = $(this).val();
if (option != "") $('.'+option).show();
});
and a few minor mods to the html
<form>
<p>
<label for="select">Goal Type</label>
<select id="typeselect" class="typeselect">
<option value=""></option>
<option value="body">Body</option>
<option value="strength">Strength</option>
<option value="distance">Distance</option>
</select>
</p>
<div class="body target">
<p><label for="body">Body</label></p>
</div>
<div class="strength target">
<p><label for="strength">Strength</label></p>
</div>
<div class="distance target">
<p><label for="distance">Distance</label></p>
</div>
</form>
You can view and edit here at codepen: http://codepen.io/anon/pen/ktesh
Give a name / Id to Select and Div's.
var x = document.getElementById("SelectId / Name").selected;
if(x==0) {
document.getElementById("body").style.display = "block";
} else {
\\ Similarly for other div to display on the basis of x
}
Try this:
$('.typeselect').change(function(){
$('div').hide();
if($(this).val() == ""){
$(this).children('option:first-child').show();
}
else
$('.' + $(this).val()).show();
});

Changing value of the input after append()

I have created a template html block with allow me to copy that block when I click on Add button. This is done via append()
How to change the value of name='category[]' input field after it has been appended?
For example:
$('#add').click(function() {
$('#LinesContainer').append($('#templatePlan').html());
var getCategory = $("#selectCategory").val();
// How to put getCategory value into category[] field?
});
Select Category and click on + button
<div>
<select id="selectCategory">
<option value="New">New</option>
<option value="Old">Old</option>
</select>
<input value="+" id="add" type="button"/>
</div>
Template Block
<div id="templatePlan" style="display:none;">
<div style='padding: 5px; border: 1px solid white; background-color: #FFA86F;'>
<select name="selectType[]">
<option>Consumer</option>
<option>Business</option>
</select>
<input name='category[]' type='hidden' value='' />
</div>
</div>
<div id="LinesContainer"> </div>
I am not sure if this is a neat way to implement it, is there alternative better way?
Just select it. I'd recommend to use .clone() for the template instead of innerHTML, that will make the selection easier. Otherwise you might have multiple category inputs and have to use that last one.
$('#add').click(function() {
$('#templatePlan').children('div').clone().appendTo('#LinesContainer')
.find('input name="category[]"').val($("#selectCategory").val());
});
//after
var getCategory = $("#selectCategory").val();
//To set the actual input
$('input[type="hidden"]').val(getCategory);
//or to update the attribute rather
$('input[type="hidden"]').attr('name', 'category[' + getCategory + ']');

How to clear the textarea value using onclick method

I'm having a listBox, when selected it, it will be printed in the textArea and beside to it I have given a clear button, so when clicked the value of the textArea has to be cleared, it works fine, now the problem is, after clearing the value in textArea and again when i select the listBox, the value is not getting printed on the textArea. What might be the problem?
Here is the code,
HTML:
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
JavaScript:
function addToExpText() {
alert("hello);
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
obj.appendChild(openP);
}
function clearTextArea(){
document.form1.textArea.value='';
}
After clearing the value in the textArea, again if i click on the listBox value and add it, it is not getting added. Pls help... Here is the implementaiton which is not working properly, may be its becaus i'm using it for the first time and i might be wrong.
http://jsfiddle.net/8dHf5/5/
Not sure why it works like that, but here are few possible fixes:
Instead of using append (to add a new aggregation function), you can use value both to add and clear:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId").value += aggreFunct;
}
function clearTextArea(){
document.getElementById("expTextId").value='';
}
Demo: http://jsfiddle.net/8dHf5/17/
Or you can use remove child nodes to clear values of textarea:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var myNode = document.getElementById("expTextId");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
​
Demo: http://jsfiddle.net/8dHf5/14/
Besides, there is a line obj.appendChild(openP); in your code, but I do not see it being available in code, so I removed it.
Another moment: in your clearTextArea you are trying to access your textarea like document.textArea - if I'm not missing something, it is IE only feature and it works with ids instead of names. It is better to use document.getElementById which is cross browser.
There was some mistake in your code.
I have modified it...
Now you are able to clear data.
Please refer below code:
<html>
<body>
<script>
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var textArea = document.getElementById("expTextId");
while (textArea.firstChild) {
textArea.removeChild(textArea.firstChild);
}
}
</script>
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
</body>
</html>

Display the selected value of a Drop down list in a text field (javascript)

For Example:
These are the items in a drop down list.
<select name="cmbitems" id="cmbitems">
<option value="price1">blue</option>
<option value="price2">green</option>
<option value="price3">red</option>
</select>
When the user selects blue, i want to display the value of price1 in a text field below:
<input type="text" name="txtprice" id="txtprice" onClick="checkPrice()">
Thank you for answering
All you need to do is set the value of the input to the value of the select, in a select.onchange event handler.
var select = document.getElementById('cmbitems');
var input = document.getElementById('txtprice');
select.onchange = function() {
input.value = select.value;
}
Here is a link to a jsFiddle demo
This is the brute force way to look up the currently selected option, check its value and use its display text to update your input. Like Daniele suggested, if you have jquery at your disposal, this gets much, much easier. But if you can't use a JS framework for any reason, this should get you what you need.
<select name="cmbitems" id="cmbitems" onchange="updateTextField()">
...
</select>
<input type="text" ..... />
<script type="text/javascript">
function updateTextField()
{
var select = document.getElementById("cmbitems");
var option = select.options[select.selectedIndex];
if (option.id == "price1")
{
document.getElementById("txtprice").value = option.text;
}
}
</script>
$.on('change', '#cmbitems', function() {
$('#txtprice').val($('#cmbitems option:selected').val());
});
If you are using jquery just go with
$('select.foo option:selected').val(); // get the value from a dropdown select
UPDATE ( I forgot to inlcude the <input> population)
First, inlcude jquery in your html file.
In the <header> you include it:
<header>
<script type="text/javascript" src="YOUR_PATH_TO_LIBRARY/jquery-1.7.1-min.js"></script>
</header>
Then
<input type="text" name="txtprice" id="txtprice" onClick="javascript:$('select.foo option:selected').val();">

Categories

Resources