Trying to search and replace in textarea based on multiple selects - javascript

I'm giving users multiple select options, and want to change parts of a textarea based on the selections. I can get each instance to work, but only for the current select. When I change another select, the previous one goes back to the original value.
How can I replace a string on select change, and have it stay that way if another select is changed?
<script type="text/javascript">
var textcode = document.getElementById("code").innerHTML;
var bckcolor = document.querySelector('#bckcolor');
var txtinner = document.querySelector('#txtinner');
var submitbtn = document.querySelector('#submitbtn');
bckcolor.addEventListener('change', e => {
document.getElementById("code").innerHTML = textcode.replace("backcolor = \"#242323\"", "backcolor = \"" + bckcolor.value + "\"");
})
txtinner.addEventListener('change', e => {
document.getElementById("code").innerHTML = textcode.replace("textinner = \"#c6c6c6\"", "textinner = \"" + txtinner.value + "\"");
})
submitbtn.addEventListener('change', e => {
document.getElementById("code").innerHTML = textcode.replace("subbtn = \"linear-gradient(225deg, #ee69ff 0%, #955af9 100%)\"", "subbtn = \"" + submitbtn.value + "\"");
})
</script>
<select name="bckcolor" id="bckcolor">
<option value="#242323">#242323 (default)</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
<br/>
<select name="txtinner" id="txtinner">
<option value="#c6c6c6">#c6c6c6 (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<br/>
<select name="submitbtn" id="submitbtn">
<option value="linear-gradient(225deg, #ee69ff 0%, #955af9 100%)">linear-gradient(225deg, #ee69ff 0%, #955af9 100%) (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<textarea id="code" style="width:100%;height:300px;padding:10px;margin-bottom:10px;" disabled>
<script type="text/javascript">
var backcolor = "#242323";
var textinner = "#c6c6c6";
var subbtn = "linear-gradient(225deg, #ee69ff 0%, #955af9 100%)";
</script>
</textarea>

The fixes and some improvements with your code:
You're referencing and storing the value of innerHTML inside the textcode variable. After one select updates the value, the variable isn't updated and still contains the old text
You're always replacing the base value as your search term and not accounting for the changed text. Use regex to select the whole line
Don't use var, but let.
No need to use escape the double quotes. You can use backtick (``) around your string and include any variables within ${}.
Here's a codepen that resolves your issues (and improves upon the code a bit):
https://codepen.io/prvashisht/pen/MWBBaVv
<script>
var textcodeNode = document.getElementById("code");
var bckcolor = document.querySelector("#bckcolor");
var txtinner = document.querySelector("#txtinner");
var submitbtn = document.querySelector("#submitbtn");
bckcolor.addEventListener("change", (e) => {
textcodeNode.innerHTML = textcodeNode.innerHTML.replace(
/backcolor.*/g,
`backcolor = "${bckcolor.value}"`
);
});
txtinner.addEventListener("change", (e) => {
textcodeNode.innerHTML = textcodeNode.innerHTML.replace(
/textinner.*/g,
`textinner = "${txtinner.value}"`
);
});
submitbtn.addEventListener("change", (e) => {
textcodeNode.innerHTML = textcodeNode.innerHTML.replace(
/subbtn.*/g,
`subbtn = "${submitbtn.value}"`
);
});
</script>
<select name="bckcolor" id="bckcolor">
<option value="#242323">#242323 (default)</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
<br />
<select name="txtinner" id="txtinner">
<option value="#c6c6c6">#c6c6c6 (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<br />
<select name="submitbtn" id="submitbtn">
<option value="linear-gradient(225deg, #ee69ff 0%, #955af9 100%)">linear-gradient(225deg, #ee69ff 0%, #955af9 100%) (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<textarea id="code" style="width:100%;height:300px;padding:10px;margin-bottom:10px;" disabled>
<script type="text/javascript">
var backcolor = "#242323";
var textinner = "#c6c6c6";
var subbtn = "linear-gradient(225deg, #ee69ff 0%, #955af9 100%)";
</script>
</textarea>

Your code doesn't exactly do anything, probably you are omitted some parts of it. So can't tell what is going on. Maybe you gotta rephrase your question or add missing parts to your code.
Another thing is you don't consider when there is a change your replace literals are still based on the previous values.
That's being said, I am guessing: if you are "posting" this as a form, then that's a normal behavior because you are re-navigating to the page, so default values are back, either you gotta handle POST values and assign to selects or;
You can tackle this a bit differently by using JS's Template Strings;
<script type="text/javascript">
//This is a reference object, you'll keep your changes here.
var values ={
back:"#242323",
textinner:"#c6c6c6",
subbttn:"linear-gradient(225deg, #ee69ff 0%, #955af9 100%)"
}
function updateTextArea(change,value){
//Update your reference object values.
if(change){
values[change] = value
}
//and create a string the way you wanted
let newCode = `<script type="text/javascript">\n`
newCode+= `var backcolor = ${values.back};\n`;
newCode+= `var textinner = ${values.textinner};\n`
newCode+= `var subbtn = ${values.subbttn};\n`
newCode+= `<\/script>`
//Then update your textarea element.
document.getElementById("code").value = newCode
}
</script>
<select name="bckcolor" id="bckcolor">
<option value="#242323">#242323 (default)</option>
<option value="blue">blue</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
<br/>
<select name="txtinner" id="txtinner">
<option value="#c6c6c6">#c6c6c6 (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<br/>
<select name="submitbtn" id="submitbtn">
<option value="linear-gradient(225deg, #ee69ff 0%, #955af9 100%)">linear-gradient(225deg, #ee69ff 0%, #955af9 100%) (default)</option>
<option value="black">black</option>
<option value="white">white</option>
<option value="blue">blue</option>
</select>
<textarea id="code" style="width:100%;height:300px;padding:10px;margin-bottom:10px;" disabled></textarea>
<script>
//This block is after the element because otherwise wouldn't be accessible.
var textcode = document.getElementById("code").innerHTML;
var bckcolor = document.querySelector('#bckcolor');
var txtinner = document.querySelector('#txtinner');
var submitbtn = document.querySelector('#submitbtn');
//All these event listeners can use same function, therefore;
bckcolor.addEventListener('change', e => {
updateTextArea("back",bckcolor.value)
})
txtinner.addEventListener('change', e => {
updateTextArea("textinner",txtinner.value)
})
submitbtn.addEventListener('change', e => {
updateTextArea("subbttn",submitbtn.value)
})
//Initially we run once without parameters, to use it with defaults.
updateTextArea()
</script>

Related

Make image change with selecting different option in dropdown - Javascript / Html

I have a system where you are able to choose a car. You can then choose the transmission and color. Different cars and transmissions bring up different colors. Not sure how to make an image appear of a car when a color is chosen. So for example I choose the rs6 and automatic and then the black color. I would then want an image to appear depending on the color chosen. How would I program it so different cars and colors bring up different images. Im relatively new to coding. Any help would be aprreciated.
HTML
<!DOCTYPE html>
<html><head>
<title></title>
</head>
<body>
<form name="CarConfigurator">
<select id="car" name="Car_make">
<option value="" selected="selected">Which car?</option>
<option value="car1">Audi RS6</option>
<option value="car2">BMW M4</option>
<option value="car3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select id="trans" name="A_M">
<option value="" selected="selected">What trans?</option>
<option value="auto">Automatic</option>
<option value="man">Manual</option>
</select>
<br>
<br>
<select id="color" name="Color">
<option value="" selected="selected">What Color?</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="white">White</option>
<option value="green">Green</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1 /jquery.min.js"/
</script>
<script src="configurator.js"></script>
</body>
</html>
Javascript
$("#car").change(function () {
transmission();
});
$("#trans").change(function () {
transmission();
});
function transmission() {
if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
$("option[value$='red']").hide();
$("option[value$='white']").hide();
$("option[value$='green']").hide();
} else {
$("option[value$='red']").show();
$("option[value$='white']").show();
$("option[value$='green']").show();
}
}
For now it is only working for Audi - Automatic - black and blue to show you the basic idea but it is repeating code and you can do the same for the rest of the cars too.
In this example I am setting the src of the image as the car selected. For example if you select car1 and man and red then src of the image as car1manred.jpg, also I'm changing the alt attribute as well so that you can see the change.
you have to do a lot of manual work. I have created an object for the data that will determine how many cars you have in each category. It would be better if you use JSON for that.
Also I have made car1autoblack (which gets the src of the images) as an array but you can make it as an object and include other things about the cars in this category. for example name, price, availability and much more
$("#car").change(function () {
transmission();
selection();
});
$("#trans").change(function () {
transmission();
selection();
});
$("#color").change(function () {
selection();
});
var cars = {
car1autoblack:["car1auto1black1.png","car1auto1black2.jpg"],
car1autoblue:["car1auto1blue1.png","car1auto1blue2.jpg","car1auto1blue3.jpeg"]
}
function transmission() {
if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
$("option[value$='red']").hide();
$("option[value$='white']").hide();
$("option[value$='green']").hide();
} else {
$("option[value$='red']").show();
$("option[value$='white']").show();
$("option[value$='green']").show();
}
}
function selection(){
if ($("#car").val() && $("#trans").val() && $("#color").val()) {
var carVal = $("#car").val();
var transVal = $("#trans").val();
var colorVal = $("#color").val();
var combineVal = carVal+transVal+colorVal;
//var imageLink = combineVal+".jpg";
//$("#showImg").attr("src", imageLink);
//$("#showImg").attr("alt", imageLink);
//console.log(cars[combineVal]);
var inputDivHTML = "";
var car = cars[combineVal];
for(i in car){
inputDivHTML += "<img class='showImg' src='"+car[i]+"' alt='"+car[i]+"'/>";
}
$(".imageHere").html(inputDivHTML);
}
}
img.showImg{
width:150px;
height:70px;
margin:10px 3px;
border:1px solid red;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="CarConfigurator">
<select id="car" name="Car_make">
<option value="" selected="selected">Which car?</option>
<option value="car1">Audi RS6</option>
<option value="car2">BMW M4</option>
<option value="car3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select id="trans" name="A_M">
<option value="" selected="selected">What trans?</option>
<option value="auto">Automatic</option>
<option value="man">Manual</option>
</select>
<br>
<br>
<select id="color" name="Color">
<option value="" selected="selected">What Color?</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="white">White</option>
<option value="green">Green</option>
</select>
</form>
<div class="imageHere">
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
</div>

onchange to change text color inside contenteditable

I currently have a select box that has options of different colors, as well as a contenteditable inside a div to be used as a text editor. What I want is when I select a color from the box e.g. red, the selected text inside the contenteditable changes to red.
<select id="colorChange">
<option onchange="value="Black">Black</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Pink">Pink</option>
</select>
Onchange of options call a function and use jquery .css method to the change the text color.
function changeColor(){
var _color = $("#colorChange option:selected" ).val().toLowerCase();
$("#abc").css('color',_color)
}
Note: There is a typo in <option onchange="value="Black">Black</option>
JSFIDDLE
Here is the jQuery solution.
onchange needs to be on select.
Apply the selected color to the div.
$(function() {
var color = 'black';
$('select').change(function() {
color = $(this).val();
$('div').css('color', color);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="colorChange">
<option value="Black">Black</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Pink">Pink</option>
</select>
<br/>
<br/>
<div contenteditable="true">This text color will change based on selection</div>
Listen for the change event on the select input, grab its value then change the color of your container using CSS.
$('#colorChange').change(function(){
var selectedColor = this.value;
$('#container').css('color', selectedColor);
});
This method will work when using color names Supported by all browsers (http://www.w3schools.com/cssref/css_colors.asp) if you want custom colors you will need to either set the value of the options in the select input to the HEX(#) value for the color required or pass selectedColour through a switch statement to determine the color code.
Javascript version. I really hope I am not doing your homework.
document.getElementById('colorChange').addEventListener('change',function(event){
var val = event.target.value;
var div = document.getElementById('editableDiv');
div.style.color = val;
});
Try this:)
$('#colorChange').on('change', function() {
$color = this.value
$("select option:selected").css("color", $color);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="colorChange">
<option onchange="value="Black">Black</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Yellow">Yellow</option>
<option value="Pink">Pink</option>
</select>

HTML Forms with drop down items, how to remove it from in realtime for the next form?

I have a JSP page that is populating 3 different drop down menus.
They are all populated the same. I am looking for a javascript way that in realtime if they choose one from the dropdown the next one they go to the dropdown list won't have that option in it.
Say you have 3 selects "Select1","Select2",and "Select3". Add onchange event to "Select1":
<script language="javascript">
function Select1_OnChange() {
var elemSelect1 = document.getElementById("Select1");
var elemSelect2 = document.getElementById("Select2");
var elemSelect3 = document.getElementById("Select3");
var selValue = elemSelect1.options[elemSelect1.selectedIndex].value;
elemSelect2.remove(getIndexFromValue(elemSelect2,selValue));
elemSelect3.remove(getIndexFromValue(elemSelect3, selValue));
}
function Select2_OnChange() {
var elemSelect2 = document.getElementById("Select2");
var elemSelect3 = document.getElementById("Select3");
var selValue = elemSelect2.options[elemSelect2.selectedIndex].value;
elemSelect3.remove(getIndexFromValue(elemSelect3, selValue));
}
function getIndexFromValue(objSelect,strValue) {
var ret;
for (i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].value == strValue) {
ret = i;
}
}
return ret;
}
</script>
Tags might look like:
<select id="Select1" name="Select1" size="1" onchange="Select1_OnChange()>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<select id="Select2" name="Select2" size="1" onchange="Select2_OnChange()>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<select id="Select3" name="Select3" size="1">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>

Getting value of drop down list JavaScript

How to make that the all selected options, not the values, but the actual text, would be displayed somewhere?
Html:
<h1>Made your PC:</h1>
<div>
<label>Processeor: </label><select id="processor" name="processor">
<option class="label" value>Select Processor</option>
<!-- Home Ware -->
<option value="P1">Processor 1</option>
<option value="P2">Processor 2</option>
<option value="P3">Processor 3</option>
<option value="P4">Processor 4</option>
</select>
</div>
<p><strong>Only compatible components will show.</strong></p>
<div>
<label>Select motherboard: </label><select id="motherboard" name="motherboard" class="subcat" disabled="disabled">
<option class="label" value>Select Motherboard</option>
<!-- Home Ware -->
<option rel="P1 P2" value="AS1">ASUS RAMPAGE V EXTREME</option>
<option rel="P2 P3" value="AS2">ASUS ATX DDR3 2600 LGA</option>
<option rel="P1 P3 P4" value="GB1">Gigabyte AM3+</option>
<option rel="P2 P4" value="MSI1">MSI ATX DDR3 2600 LGA 1150</option>
</select>
</div>
<div>
<label>Select RAM: </label> <select disabled="disabled" class="subcat" id="RAM" name="RAM">
<option class="label" value>RAM Memory</option>
<option rel="AS1 AS2 GB1" value="KI1">Kingston Value RAM</option>
<option rel="AS1 AS2 MSI1" value="P5KPL">P5KPL-AM SE</option>
<option rel="MSI1 GB1" value="960GM">960GM-VGS3 FX </option>
</select>
</div>
<div>
<label>Select Video Board: </label> <select disabled="disabled" class="subcat" id="video-card" name="video-card">
<option class="label" value>Video Card</option>
<option rel="MSI1 AS2" value="EVGA8400">EVGA GeForce 8400 GS</option>
<option rel="AS1" value="XFXAMD">XFX AMD Radeon HD 5450</option>
<option rel="MSI1 GB1" value="GTX750Ti">EVGA GeForce GTX 750Ti SC</option>
</select>
</div>
Javascript:
$(function(){
var $supcat = $("#processor"),
$cat = $("#motherboard"),
$subcat = $(".subcat");
$supcat.on("change",function(){
var _rel = $(this).val();
$cat.find("option").attr("style","");
$cat.val("");
if(!_rel) return $cat.prop("disabled",true);
$cat.find("[rel~='"+_rel+"']").show();
$cat.prop("disabled",false);
});
$cat.on("change",function(){
var _rel = $(this).val();
$subcat.find("option").attr("style","");
$subcat.val("");
if(!_rel) return $subcat.prop("disabled",true);
$subcat.find("[rel~='"+_rel+"']").show();
$subcat.prop("disabled",false);
});
});
I tried this one code that was posted earlier, but it only display one selection, right after picking, is there any way it could display all the selections and with my random text, like "Your selections"?:
<script>
function myNewFunction(sel)
{
alert(sel.options[sel.selectedIndex].text);
}
</script>
<select id="box1" onChange="myNewFunction(this);" >
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
This should give the actual label text, not the value, for a given select-element.
$(selector).find(":checked").html()
So if you want to show all of them, you could do something like this:
$("#video-card").on("change", function () {
var choices = [];
$("select").each(function() {
choices.push($(this).find(":checked").html());
});
alert("You selected: " + choices.join(', '));
})
And here's a codepen for demo purposes
http://codepen.io/anon/pen/XbjKYQ
function myNewFunction(sel) {
alert($(sel).val());
}
This should actually be working.
If that doesn't work, try to place a window.setTimeout(function() { ... }, 10); around your alert. It's possible that the browser calls the myNewFunction() method before it updates the selection value when the user clicks on one option.
EDIT: If you want the text instead of the value, use
alert($(sel).find("option:selected").text());
You need to loop through each of the selects, not just the first one:
function updateOutput() {
var selects = document.getElementsByTagName('SELECT');
var output = document.getElementById('output');
var arr = [];
for (i=0; i < selects.length; i++) {
arr.push(selects[i].options[selects[i].selectedIndex].text);
}
output.innerHTML = arr.join('; ');
return arr;
}
In this case, I push all the values into an array and then join the array values at the end to create the final string.
I updated a codepen provided earlier: http://codepen.io/anon/pen/WvGxgz

Cannot get function to change pictures to work

I have updated the code to this still does not seem to work I have validates the js file is pointed correctly but when I click any option the picture refuses to update.
Here's is my code:
function color() {
if (document.getElementById('carcolor').value == 'Red') {
document.getElementById('car_pic').src = 'image/Red.jpg';
}
if (document.getElementById('carcolor').value == 'Blue') {
document.getElementById('car_pic').src = 'image/BLue.jpg';
}
if (document.getElementById('carcolor').value == 'Silver') {
document.getElementById('car_pic').src = 'image/Silver.jpg';
}
if (document.getElementById('carcolor').value == 'White') {
document.getElementById('ccar_pic').src = 'image/White.jpg';
}
if (document.getElementById('carcolor').value == 'Black') {
document.getElementById('car_pic').src = 'image/Black.jpg';
}
}
checkcolor();
<div id="select1">
<h1>Choose A Color</h1>
<select name="color" size="5" id="carcolor">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Silver">Silver</option>
<option value="White">White</option>
<option value="Black">Black</option>
</select>
<img src="" alt="car picture" id="car_pic">
</div>
Multiple problems:
id can't contain whitespaces
You were using wrong ids in your JS
You were attaching ids to the wrong elements in your html
You were calling checkcolor but defined the function as color.
Better avoid inline event handlers
Avoid getting the same DOM element multiple times, better store it in a variable
You use if conditionals in a wrong way.
Instead of so many conditionals, you could use an object that gives the URL of the image given the selected value.
var sel = document.getElementById('select1'),
img = document.getElementById('car_pic'),
imgURLs = {
Red: 'image/Red.jpg',
Blue: 'image/Blue.jpg',
Silver: 'image/Silver.jpg',
White: 'image/White.jpg',
Black: 'image/Black.jpg'
};
function checkcolor() {
img.src = imgURLs[sel.value];
}
sel.onchange = checkcolor;
checkcolor();
<div>
<h1>Choose A Color</h1>
<select name="color" size="5" id="select1">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Silver">Silver</option>
<option value="White">White</option>
<option value="Black">Black</option>
</select>
<img src="" alt="car picture" id="car_pic">
</div>
If all image URLs follow the same pattern, consider
img.src = 'image/' + sel.value + '.jpg';
var sel = document.getElementById('select1'),
img = document.getElementById('car_pic');
function checkcolor() {
img.src = 'image/' + sel.value + '.jpg';
}
sel.onchange = checkcolor;
checkcolor();
<div>
<h1>Choose A Color</h1>
<select name="color" size="5" id="select1">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Silver">Silver</option>
<option value="White">White</option>
<option value="Black">Black</option>
</select>
<img src="" alt="car picture" id="car_pic">
</div>
document.getElementById relates to the ID within your tag, your pointing it towards the alternative name of the the image tag. Also you assigning statements are outside your brackets;
if (document.getElementById('select1').value == 'Red'){} <-- Here
document.getElementById('car picture').src ='image/Red.jpg';
to
if (document.getElementById('select1').value == 'Red'){
document.getElementById('car picture').src ='image/Red.jpg';
}
hope it helps
Edit: Was posted after the two comments below your question, both pretty much explain it

Categories