Dynamicaly Changing the <textarea > size,style - javascript

How can i change the field size diynamicaly?
I have a select field and there are 3 options with different values.
So if the user selects one of them in the you see the values.
But how can i change the size that the values from option field fits in the
function changeText()
{
var select = document.getElementById("surl");
var textfield = document.getElementById("turl");
var bold = document.getElementById("burl");
var link = document.getElementById("linkText");
if(bold.style.display == "none")
bold.style.display = "";
//if(link.innerHtml)
bold.innerHtml = select.value;
//if(link.innerHTML !="")
link.innerHTML= select.value;
textfield.value = select.value;
}
<b>Sample: </b><select id="surl" onchange="changeText();" style="visibility: visible;" name="linkText">
<option>Select LinkText</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Want sign? http://www.doesntexist.dsdsd</a>">
Variant1
</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Wanna killme? http://www.doesntexist.dsdsd</a>">
Variant 2
</option>
</select>
<br />
<div class="succes">
<span id="burl" style="display: none"><br /><a id="linkText" href="http://www.doesntexist/"></a></span>
</div>
</p>
<p>
<textarea id="turl" style="">
text...
</textarea>
</p>

Sorry, I must’ve misunderstood your problem.
So you want to resize a textarea dynamically based on what, its contents? You could use the jQuery autoResize plugin for this…

A quick 'n' dirty jQuery solution would be the following:
$('input#foo-option-1').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '150px');
}
});
$('input#foo-option-2').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '250px');
}
});
$('input#foo-option-3').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '350px');
}
});
Of course, this code isn’t very DRY. Moreover, modifying CSS properties through JavaScript is never a very good idea — it’s better to add classes dynamically through JS and specify the actual CSS in your CSS files (duh).

For example:
<script type="text/javascript">
document.getElementById("textarea_id").style.width = "300px";
document.getElementById("textarea_id").style.width = "200px";
</script>

First of all i thought there are more devs who can help; any way here is the answer
first create a function which calculates the strlen
function strlen(strVar)
{
return(strVar.length)
}
Second create a var tfcount
var tfcount = strlen(select.value);
and finaly
textfield.style.width = tfcount < 110 ? tfcount = 110 : 3.5*tfcount+"px";
textfield.style.height = tfcount < 110 ? tfcount = 110 : tfcount/2.5+"px";

Related

How to copy a string from a <div> and past in an <input>?

Code of Note i want copy is : <strong title="Note VF" class="note-a-copier" style="cursor: pointer;" data-clipboard-text="7.6">7.6</strong>
I copy the Note with : data-clipboard-text
Normally past on :
HTML :
<select>
<option id="note-a-coller"></option>
</select>
JavaScript :
<script>
const btnsnote = document.getElementsByClassName('note-a-copier');
for(btn of btnsnote) {
btn.addEventListener(\'click\', elt => {
const input = document.getElementById('note-a-coller');
select.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
</script>
But when I click on the note, it should stick directly in the but it doesn't work.
Example Working Code : https://jsfiddle.net/rjds289g/
const btnsadp = document.getElementsByClassName('adp-a-copier');
for(btn of btnsadp)
{
btn.addEventListener('click', elt => {
const input = document.getElementById('adp-a-coller');
input.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Past : <input type="text" size="40" name="annee" value="" id="adp-a-coller" required />
On JSFiddle : https://jsfiddle.net/rjds289g/3/
I want like this, but with < select > and i don't know how to do this, so if anyone can help me :)
Select value will change with any value inside of it .. in your case the value isn't an option in a select so you need to append it first
const btnsadp = document.getElementsByClassName('adp-a-copier');
for(btn of btnsadp)
{
btn.addEventListener('click', elt => {
var The_Select = document.getElementById('adp-a-coller'),
The_Text = document.createTextNode(elt.target.dataset.clipboardText),
The_option = document.createElement("OPTION");
The_option.appendChild(The_Text);
The_Select.appendChild(The_option);
The_Select.value = elt.target.dataset.clipboardText;
return false;
}, false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Past : <select id="adp-a-coller"><option>1</option></select>
And this is the jquery version for me it's much easier to work with
$(document).on('click' , '.adp-a-copier' , function(){
var $this = $(this),
text = $this.data('clipboard-text');
if(!$this.hasClass('appended')){
$this.addClass('appended');
$('#adp-a-coller').append('<option value="'+text+'">'+text+'</option>').val(text);
}else{
$('#adp-a-coller').val(text);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Copy : <div class="adp-a-copier" data-clipboard-text="2001" style="cursor: pointer;">2001</div>
Copy : <div class="adp-a-copier" data-clipboard-text="2003" style="cursor: pointer;">2003</div>
Copy : <div class="adp-a-copier" data-clipboard-text="2005" style="cursor: pointer;">2005</div>
Past : <select id="adp-a-coller"></select>
Explanation : I used the appended class in jquery snippet to append the text just one time to the select even you keep clicking it will remain just one append
Read about how to fill a select with JS. the logic is easy.
You just have to add the div content in an array and after it refill combo with your array content

Dropdown menu to change background image does nothing

This is my first question on Stack Overflow (so sorry if I do something wrong)
Anyway, I'm trying to create a drop down menu that changes the background image of the website. However, when selecting the options, nothing happens.
EDIT My WORKING code for this is:
function changeTheme()
{
var e = document.getElementById("bg");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "default")
{
document.body.style.backgroundImage = "url(Thresh_BG.png)";
}
if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url(dark star.png)";
}
}
<div id="bg">
<form>
<select name="bg" id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>
</div>
First, you have id collision in your HTML. You may change the id of your div to be anything other than bg; let's say bg1.
Then, you need to access the value of an option rather than its text, so it will be:
var strUser = e.options[e.selectedIndex].value;
Firstly, i would declare your variable outside the function with a more specific name than 'e'.
Also, you should add inner [single] quotes to your image .
It's always a good idea to include the full path even if it's local on your server. Makes it easier to spot an error. I include a jsbin witn my own images (they are used in the below snippet also)
Hope this helps
Welcome to stackoverflow!
var selecte = document.getElementById("bg");
function changeTheme() {
var strUser = selecte.options[selecte.selectedIndex];
if (strUser.value == "default") {
document.body.style.backgroundImage = "url('http://www.rachelgallen.com/images/purpleflowers.jpg')";
}
if (strUser.value == "darkstar") {
document.body.style.backgroundImage = "url('http://www.rachelgallen.com/images/yellowflowers.jpg')";
}
};
<form>
<select id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>
for startes, I'm pretty sure you need more quotes.
Try changing it like this:
***Code***
if (strUser == "default")
{
document.body.style.backgroundImage = "url('Thresh_BG.png')";
}
if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url('dark star.png')";
}
If you use the URL like that, you'll need to make sure that the background-images are in the same folder as the HTML. (Which is bad practice?). Better make a 'content' folder and make an 'images' folder there. Of course you would have to update your URL's to match the new location of your images. (relative, of course).
If I were you, I'd use a switch statement too (if you want to upgrade your webpage and you have more than two options, it's going to be hard to put multiple if-statements.
Something like this:
switch(strUser)
case "default":
document.body.style.backgroundImage = "url('Thresh_BG.png')";
break;
case "darkstar":
document.body.style.backgroundImage = "url('dark star.png')";
break;
***more options here***
default: break;
Edit
I also see you have two ID's the same, which is also bad practice as your Javascript doesn't know which one to pick. So you might want to change that.
Another small remarkt, are you sure you need the 'text' value of the select? You might want to ask for the value instead of the text.
function changeTheme(e)
{
var e = document.getElementById("bg");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "default")
{
// document.body.style.backgroundImage = "url('img_tree.png')";
document.body.style.backgroundImage = "url('http://kenrockwell.com/nikon/d5300/sample-images/DSC_0024.jpg')";
}
else if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url('https://www.w3schools.com/css/trolltunga.jpg')";
}
}
please check the jsfiddle link:
https://jsfiddle.net/jayesh24/bdxLvvbo/
here my working code check it
function changeTheme() {
console.log('work');
var e = document.getElementById("bg").value;
if (e == "default") {
document.body.style.backgroundImage = "url(1.jpg)";
}
if (e == "darkstar") {
document.body.style.backgroundImage = "url(2.jpg)";
}
}
<html>
<body background="1.jpg">
<div id="abc">
</div>
<form>
<select name="bg" id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>
</body>
</html>

Replace CSS line with PHP Conditional

I'm looking to replace a css line when a certain condition is met. I have a bunch of data that appears when I press Ok. Depending on what is selected in a combo-box I want the text to be red or black. I tried in javascript but it isn't working.
EDIT: I managed to change to red when I press OK, though because it reloads the data it returns to original black.
time.css
.time-title {
width:auto;
color:black;
position:absolute;
z-index:5;
}
index.php - part of it
<label> Visualizar: </label>
<select id="estado">
<option value="Normal"> Normal </option>
<option value="Crítico"> Crítico </option>
</select>
<label id="okbt">Ok</label>
</div>
<div id='placement'></div>
<script type='text/javascript'>
$("#okbt").on("click", function(){
var v1 = $("#cproc").val();
var v2 = $("#estado").val();
var tg1 = {};
var doc_ht = $(document).height();
$("#placement").css({"height":"510px"});
$(function () {
if (v2 === "Crítico") {
$(".time-title").css({"color":"red"});}
tg1 = $("#placement").timeline({
"min_zoom":1,
"max_zoom":30,
"image_lane_height":100,
"icon_folder":"timeglider/icons/",
"data_source":"pptimeline.php?ty="+v1+"&est="+v2, //add select value to url
"constrain_to_data":false
});
tg_actor = tg1.data("timeline");
var tg1_actor = tg1.data("timeline");
window.setTimeout(function() {
tg1_actor.refresh();
}, 1000);
});
});
</script>
Your JavaScript is most-likely being executed before the DOM is ready.
Try wrapping the code within a document.ready function:
<script type='text/javascript'>
$(document).ready(function() {
var v3 = $("#estado").val();
if (v3 === "Crítico")
{
$(".time-title").css({"color":"red"});
}
});
</script>

How to remove a selected option from html select?

My actual question is quite bit complicated compared to its title. I am very new to Javascript and jQuery so please bear with me.
I would suggest that you run this code first before reading my question so you can understand what I'm trying to do.
<html>
<head>
<script type="text/javascript" src="jquery1.6.4min.js"></script>
<script type="text/javascript" >
var selectedAddFootballPlayerId = '';
var selectedAddFootballPlayerName = '';
var selectedRemoveFootballPlayerId = '';
var selectedRemoveFootballPlayerName = '';
$(document).ready(function() {
$('#listboxFootballPlayers option').click(function() {
selectedAddFootballPlayerId = $(this).attr('value');
selectedAddFootballPlayerName = $(this).text();
});
$('#selectedFootballPlayers option').click(function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
$('input#btnAddFootballPlayerToList').click(function() {
if (selectedAddFootballPlayerId == '') {
alert("Select a football player to be added from the list.");
} else {
var option = new Option(selectedAddFootballPlayerName , selectedAddFootballPlayerId);
$(option).html(selectedAddFootballPlayerName);
$('#selectedFootballPlayers').append(option);
selectedAddFootballPlayerId = '';
selectedAddFootballPlayerName = '';
}
});
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (selectedRemoveFootballPlayerId == '') {
alert("Select a football player to be removed from the list.");
} else {
var option = new Option(selectedRemoveFootballPlayerName , selectedRemoveFootballPlayerId);
$(option).html(selectedRemoveFootballPlayerName);
$('#listboxFootballPlayers').append(option);
selectedRemoveFootballPlayerId = '';
selectedRemoveFootballPlayerName = '';
}
});
});
</script>
</head>
<body>
<table>
<tr>
<td>
<select id="listboxFootballPlayers" size="5" multiple="multiple" style="width: 200px;">
<option value="l1">Cristiano Ronaldo</option>
<option value="l2">Ricardo Kaka</option>
<option value="l3">Lionel Messi</option>
<option value="l4">Gerd Muller</option>
<option value="l5">Johan Crujjf</option>
<option value="l6">Franz Beckenbauer</option>
<option value="l7">David Beckham</option>
</select>
</td>
<td>
<table>
<tr><td><input type="button" id="btnAddFootballPlayerToList" value="->" /> </td></tr>
<tr><td><input type="button" id="btnRemoveFootballPlayerFromList" value="<-" /></td></tr>
</table>
</td>
<td>
<select id="selectedFootballPlayers" size="5" multiple="multiple" style="width: 200px;"></select>
</td>
</tr>
</table>
</body>
</html>
Before I start with the question please take note:
#listboxFootballPlayers - The listbox on the left
#selectedFootballPlayers - The listbox on the right
I have 2 questions:
How can I remove the selected item / option from #listboxFootballPlayers after I clicked on -> button.
Why is it that when I click on <- after I selected an item / option from #selectedFootballPlayers it gives me a message Select a football player to be removed from the list. It seems to me that it doesn't assign the value on the variable selectedRemoveFootballPlayerId.
Please ask me if there are something that are not clear with my question. Please help.
Here is the jsfiddle link: http://jsfiddle.net/7vspM/
$(document).ready(function() {
$('#listboxFootballPlayers option').click(function() {
selectedAddFootballPlayerId = $(this).attr('value');
selectedAddFootballPlayerName = $(this).text();
});
$('#selectedFootballPlayers option').live('click', // `live()` event for `option` bcoz, option in this select will
// create after DOM ready
function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
$('input#btnAddFootballPlayerToList').click(function() {
if (selectedAddFootballPlayerId == '') {
alert("Select a football player to be added from the list.");
} else {
var option = new Option(selectedAddFootballPlayerName, selectedAddFootballPlayerId);
$(option).html(selectedAddFootballPlayerName);
$('#selectedFootballPlayers').append(option);
$('#listboxFootballPlayers option:selected').remove(); // remove selected option
selectedAddFootballPlayerId = '';
selectedAddFootballPlayerName = '';
}
});
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (selectedRemoveFootballPlayerId == '') {
alert("Select a football player to be removed from the list.");
} else {
var option = new Option(selectedRemoveFootballPlayerName, selectedRemoveFootballPlayerId);
$(option).html(selectedRemoveFootballPlayerName);
$('#selectedFootballPlayers option:selected').remove(); // remove selected option
$('#listboxFootballPlayers').append(option);
selectedRemoveFootballPlayerId = '';
selectedRemoveFootballPlayerName = '';
}
});
});
Regarding 2):
The problem is that you assign the click functionality before you create the element to assign it to. When you create your option you should assign it instead, like this:
$(option).click(function() {
selectedRemoveFootballPlayerId = $(this).attr('value');
selectedRemoveFootballPlayerName = $(this).text();
});
Regarding question one, it's somewhat easier to simply move the selected option element from one list to the other:
$('#listboxFootballPlayers option:selected').appendTo('#selectedFootballPlayers');
I've commented out the lines that don't appear to be needed in the JS Fiddle demo.
As for your second question, I've rewritten the if/else statement:
$('input#btnRemoveFootballPlayerFromList').click(function() {
if (!$('#selectedFootballPlayers option:selected')){
alert("First select a player to remove.");
}
else {
$('#selectedFootballPlayers option:selected').appendTo('#listboxFootballPlayers ');
}
});
JS Fiddle demo.
References:
:selected.
appendTo().

Code to detect option value does not work as expected

I was attempting to do some string comparisons in javascript. I have seen several tutorials and examples but they do not seem to work. I am missing something fundamental?
Attempt 1
function addAspect(aspect) {
var print = document.createElement('p');
var ptext;
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
Then I found this example to which all readers said it worked fine
function addAspect() {
var print = document.createElement('p');
var ptext;
var aspect = String(document.getElementById("aspectResult").value);
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
I also tried .toString() as well as the '===' exact match comparison.
Full code
<html>
<head>
<script type="text/javascript">
function addAspect()
{
var print = document.createElement('p');
var ptext;
var aspect = document.getElementById("aspectResult").value;
if (aspect == "Option1"){
ptext = document.createTextNode("This is option1");
}
print.appendChild(ptext);
document.getElementById("mainBlock").appendChild(print);
}
</script>
</head>
<body>
<form>
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
<input type="button" value="Check" onclick="addAspect()"/>
</form>
<span id="mainBlock">&nbsp</span>
</body>
</html>
Any suggestions?
First, a small introduction to how dropdowns work:
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
To read the selected value from the dropdown, you should do this:
var dropdown = document.getElementById('aspectResult'),
selectedValue = dropdown.options[dropdown.selectedIndex].value;
Then, you create the <p> element with a text node inside:
var p = document.createElement('p'),
txt;
if (selectedValue == 'Option1') {
txt = document.createTextNode('This is option 1');
}
Afterwards, you can append the newly created paragraph to the container of your choice:
var container = document.getElementById('mainBlock');
if (txt) {
p.appendChild(txt);
container.appendChild(p);
}
All together now!
If you are trying to add the ptext to the paragraph, you need to add two lines to the end:
function addAspect(aspect) {
var prnt = document.createElement('p');
var ptext;
if( aspect == "Option1" ) {
ptext = document.createTextNode("This is option1");
prnt.appendChild(ptext); // Add the text to the paragraph
document.body.appendChild(prnt); // Add the paragraph to the document
}
}
Your function creates a text node but then does nothing with it, so you code appears to do nothing at all. You need to append the text node to an element somewhere in the DOM:
document.body.appendChild(ptext);
Your full code appears to be working fine in IE9, Firefox 4 and Chrome 11. See http://jsbin.com/ekura5/.

Categories