Using JavaScript how convert string contains CSV value like
1;option 1;2;Option 2;3;Option 3
To
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
The first thing I note is, it is in a single line. It would be better if the source is like:
1;Option 1
2;Option 2
3;Option 3
And once this is done, you need to get it by reading the file or getting it from user input using a textarea or something similar.
You can parse the contents this way:
function parseIt()
{
splitValues = document.getElementById("input").value.split("\n");
if (splitValues.length > 0)
{
document.getElementById("vals").style.display = 'inline';
console.log(splitValues);
for (i = 0; i < splitValues.length; i++)
document.getElementById("vals").innerHTML += '<option value="' + splitValues[i].split(";")[0] + '">' + splitValues[i].split(";")[1] + '</option>';
}
}
Fiddle: http://jsfiddle.net/praveenscience/ZbJps/
If you have the input in a single line like this:
Then this function will do it:
function parseIt()
{
splitValues = document.getElementById("input").value.split(";");
if (splitValues.length > 0 && splitValues.length % 2 == 0)
{
document.getElementById("vals").style.display = 'inline';
document.getElementById("vals").innerHTML = "";
for (i = 0; i < splitValues.length; i+=2)
document.getElementById("vals").innerHTML += '<option value="' + splitValues[i] + '">' + splitValues[i+1] + '</option>';
}
}
Fiddle: http://jsfiddle.net/praveenscience/ZbJps/2/
Related
I have a form with two inputs where the user has to select a number from two different sets. The first one is from 1 to 100. The second one is from 1 to 500, but I need to show only the remaining values above the number selected in the first input. Let's say I have a script like this:
<?php
echo "<form action='process.php' method='post'>";
echo "<select id='first_set' name='first_set'>";
echo "<option value='' disabled selected hidden>select how many</option>";
for ($i = 1; $i <= 100; $i ++) {
echo "<option value='" . $i . "'>" . $i . "</option>";
}
echo "</select>";
echo "<select id='second_set' name='second_set'>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var numFirstSet = $(this).val();
if(numFirstSet){
var topSecondSet = 500;
var numRemaining = topSecondSet - numFirstSet;
for (var a = numRemaining; a < topSecondSet; a ++) {
var numToDisplay = a;
$('#second_set').html('<option value="numToDisplay">numToDisplay</option>');
}
}else{
$('#second_set').html('<option value="">Select first a value from the set before!</option>');
}
});
});
</script>
<?php
// the submit button
echo "</form>";
?>
But it doesn't work. The second_set select sadly displays the word "numToDisplay", not the calculated value (var numToDisplay) nor the text "Select first a value from the set before!".
Edit: after some suggestions, I've tried with
$('#second_set').html('<option value="' + numToDisplay + '">' + numToDisplay + '</option>');
but got a strange result: after a select done in first_set, the numToDisplay value is shown but it's always 499. That is topSecondSet - 1 ! And no set of values.
I've tried to figure out a solution and wrote this code:
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var sel_box = document.getElementById("second_set");
var numFirstSet = $(this).val();
sel_box.selectedIndex = 0;
if(numFirstSet){
var topSecondSet = 100;
var startNum = numFirstSet + 1;
for (var a = startNum; a <= topSecondSet; a ++) {
var numToDisplay = a;
var option = document.createElement("option");
option.text = numToDisplay;
sel_box.add(option);
}
}else{
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
}
});
});
</script>
Now second_set is populated after the change in first_set , but got two problems:
1) the items in second_set start from numFirstSet*10 instead of numFirstSet+1;
2) each time a change is made in first_set selection, a new set of options is added instead of substitute the previous set, despite the row
sel_box.selectedIndex = 0;
that has the goal of resetting the options before adding the new ones.
3) the code
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
gives no output, it simply does not work.
Any idea to solve the three problems as above?
Here is a solution that appends a child not using Jquery. Look at Emiel Zuurbiers comments as well. I would also be careful using if(numFirstSet) becuase if the value is 0 it will evaluate as false. I think your intended result should have a check after document.ready and not in the onchange function. That way your "Select first value" option is there at runtime.
let firstSet = document.getElementById("first_set");
$(document).ready(function() {
if (firstSet.value === "null") {
$("#second_set").html(
'<option value="">Select first a value from the set before!</option>'
);
}
$("#first_set").on("change", function() {
var numFirstSet = parseInt($(this).val());
// console.log(numFirstSet);
$("#second_set").html("");
var topSecondSet = 50;
var numRemaining = topSecondSet - numFirstSet;
for (var a = numRemaining; a < topSecondSet; a++) {
let opt = document.createElement("option");
opt.innerHTML = a;
opt.value = a;
document.getElementById("second_set").append(opt);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="first_set">
<option selected disabled value="null">Nothing</option>
<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>
</select>
<br /><br />
<select id="second_set"> </select>
I use my getHTML() function in a different function which parses through data, and I display the data as an HTML string. When the user is done filling the form, I want to send that information along with the username and examid. The username and examid are also coming from the backend at the position data[0].username and data[1].examid How can I make these two attributes into global variables, so that I can use them in my send function?
function getHTML(data){
var htmlString = "";
for(var i=0; i < data.length; i++){
htmlString += "<p>"
+ data[i].questionid + "." + "\n"
+ "Question: " + data[i].question
+ "\n" + "<input type='text' value1='"
+data[i].username+ " value2='" +data[i].examid+ "'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send(){
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for(var index = 0; index < inputText.length; index++){
input = inputText[index].value;
data.push({'text' : input});
}
data.push({'username' : username, 'examid' : examid});
}
Define your variable out of any function so they would be global
var username;
var examid;
function(){...}
function(){...}
window.username = data[i].username; and window.examid = data[i].examid.
Though you may be trying to store more than one in which case you want an array.
You are looking to use the window element if you want it in the global scope.
Try following code might help you
(function() {
var x = document.getElementById("Node").value;
document.getElementById("Node").onchange = function() {
myNode()
};
document.getElementById("mySelect1").onchange = function() {
myNotes()
};
document.getElementById("mySelect2").onclick = function() {
summary()
};
function myNode() {
x = document.getElementById("Node").value;
}
function summary() {
var a = document.getElementById("mySelect1").value;
var b = document.getElementById("mySelect2").value;
document.getElementById("5").value = a + " - " + b + " - " + x;
}
function myNotes() {
var a = document.getElementById("mySelect1").value;
var b = document.getElementById("mySelect2").value;
document.getElementById("4").value = a + " + " + b + " + " + x;
}
}
)();
Notes : <input type="text" id="4" /><br> Summary : <input type="text" id="5" /><br>
<select id="Node">
<option value="w">w
<option value="x">x
<option value="y">y
<option value="z">z
</select>
<select id="mySelect2">
<option value="a">a
<option value="b">b
<option value="c">c
<option value="d">d
</select>
<select id="mySelect1">
<option value="1">1
<option value="2">2
<option value="3">3
<option value="4">4
</select>
The following code removes dropdown list values based on text entered in a textbox.
FIDDLE DEMO
JQUERY
var ddl = ('#ddl'),
txt = ('#txt');
$(txt).change(function() {
var x = $(txt).val(),
li = $(ddl).html();
if (x.length != 0) {
$(ddl).html(li);
$(ddl + ' :not([value="' + x + '"])').remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt" type="text" placeholder="Enter a number...">
<select id="ddl">
<option value="0" selected="selected">Select...</option>
<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>
</select>
QUESTION
How to restore dropdownlist values back to initial state when a new value is entered into the textbox?
I have been attempting to use:
$(ddl).selectmenu("refresh");
but this stops the script from working as expected.
Like so
...
$(ddl).html(li);
$(ddl + ' :not([value="' + x + '"])').hide();
} else {
$(ddl + ' :not([value="' + x + '"])').show();
}
...
Instead of removing the item completely, you simply hide. When you empty the input field, re-show all the items.
You could try something like this:
var ddl = ('#ddl'),
txt = ('#txt');
$(txt).change(function () {
var x = $(txt).val(),
li = $(ddl).html();
$(ddl + ' option').show();
if (x.length != 0) {
$(ddl).html(li);
$(ddl + ' option:not([value="' + x + '"])').hide();
$(ddl + ' option[value="' + x + '"]').prop('selected',true);
}
});
I have two select box. on change event of first select box, i'm adding that text into second select box. but i don't want to add duplicate record.for this i'm using filter function,(if any text that has already added then i don't want to add again) but it's not working as i want.
html
<select id="ddlCategory">
<option value="0">Select Category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select multiple="multiple" id="my-select" name="my-select[]" class="multiDrop"> </select>
<select multiple="multiple" id="your-select" name="my-selectyour[]" class="multiDrop">
myJs:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($('#your-select > option').hasClass(getCategory)) {
$("#your-select > option").filter(function (index) {
if ($(this).html() == getText) {
return;
}
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
});
} else {
$('#your-select').html('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
Jsfiddle
Here you go... my edited fiddle: http://jsfiddle.net/stoz1m6v/2/
This way it does not duplicate the entries in myselect...
you had some checking of class/category there which I removed, because I found it incorrectly done, however I could not comprehend how exactly you wanted to check the category...
and the script goes like this... I have changed only the change handler of the my-select:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($("#your-select > option").filter(function (index) {
return $(this).html() == getText; }).length ==0) {
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
This script produce a drop down form where I can select the number of drop down fields that can be displayed. However I'm kind of stuck on that. My problem now is how to make default text field base on the value of the second drop down form? For example if I select 'Ms.' It will produce Two text field else it will just one text field.
jQuery
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val();
var i = 0;
var html = '';
for (i = 1; i <= num; i++) {
html += '<br>' + i + '. <select name="gender4-' + i + '">' + '</' + 'option>' + '<option value=' + '"m">Mr. ' + '</option' + '>' + '<option value=' + '"f">' + 'Ms. ' + '</option' + '>' + '</select' + '></br>';
}
$('#list').html(html);
});
});
HTML
<select id="bookinfo_adult" name="bookinfo_adult">
<option value="0">- SELECT -</option>
<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>
<div id="list"></div>
Not quite sure what you're asking, but I guess you want to display input fields dynamically based on the current selection in your generated select elements?
So how about this?
HTML:
<input type="text" id="bookinfo_adult">
<div id="list"></div>
CSS:
#list input { display: none; }
JS:
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val(), i = 0, html = '';
for (i = 1; i <= num; i++) {
html += '<div>' + i + '. \
<select name="gender4-'+i+'"><option/><option value="m">Mr.</option><option value="f">Ms.</option><select> \
<input type="text" class="ms"> <input type="text" class="mr">\
</div>';
}
$('#list').html(html);
});
$(document).on("change", "#list select", function(){
var parent = $(this).closest("div");
switch ($(this).val()) {
case "m": parent.find(".mr").show(); parent.find(".ms").hide(); break;
case "f": parent.find("input").show(); break;
default: parent.find("input").hide(); break;
}
});
});
I just added two text fields (hidden with CSS at first) and wrapped every "line" of your dropdown in a div for easier selection. Then a onchange handler is created that works for all elements being added to the DOM in the future (once you could use jQuery.live() for that, but it's deprecated as of version 1.7). The handler itself should be self-explanatory. ;)
Working example: http://jsfiddle.net/DfXEE/