I am trying the code given below :
var tmp1 = "3";
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'>Proses</option><option value='1'>Return</option><option value='2' >Selesai</option></select>";
$('select.status_detail_hanca').val(tmp1);
$(".tbody_detail_hanca_checking").append(status_detail_hanca);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>
</div>
but this code is not working, tmp1 value from json and this select-option in loop $.each.I am trying this code also :
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' ><option value='0'"+ if(tmp1 === '0'){$(this).append("selected")} +">Proses</option><option value='1'"+ if(tmp1 === '0'){$(this).append("selected")} +">Return</option><option value='2'"+ if(tmp1 === '0'){$(this).append("selected")} +">Selesai</option></select>";
but, its also not working.
How to solve this problem ?
Thanks guys !
You can try something like this. Also Its better to use loop and create a string than hard-coding it
var tmp1 = "3";
var optionList = ["Proses", "Return","Selesai", "TEST", "FOO"]
var status_detail_hanca = "<select class='status_detail_hanca' name='status_detail_hanca[]' >";
status_detail_hanca = optionList.reduce(function(p, c, i){
var _t = "<option value='"+i+"' ";
if(tmp1 == i){
_t += "selected='selected'";
}
_t += ">" + c + "</option>";
p += _t;
return p;
}, status_detail_hanca);
status_detail_hanca += "</select>";
$(".tbody_detail_hanca_checking").append(status_detail_hanca);
$(document).on("change", ".status_detail_hanca", function(){
console.log($(this).val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tbody_detail_hanca_checking'>
</div>
You can use .prepend(), jQuery() to prepend an <option> element to select.status_detail_hanca with value and text set to tmp1, and selected property set to true.
var tmp1 = "3";
var status_detail_hanca = `
<select class='status_detail_hanca' name='status_detail_hanca[]'>
<option value='0'>Proses</option>
<option value='1'>Return</option>
<option value='2' >Selesai</option>
</select>`;
$(".tbody_detail_hanca_checking")
.append(status_detail_hanca);
var select = $("select.status_detail_hanca")
.prepend($("<option>", {value:tmp1, selected:true, text: tmp1}));
console.log(select.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class='tbody_detail_hanca_checking'>
</div>
//Selection on base of select option text
$(".status_detail_hanca option:contains("+ $.trim("Text you want to select") +")").attr('selected', 'selected');
//Selection on base of select option value
$('.status_detail_hanca').val(name);
add dot before class name from selecting element by class i.e $('.ClassName').opertion();
Related
Let say I have this variable html which contain these select options:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
How can I programmatically select an option which is inside the html variable so when I append them to somewhere, for example
$(this).children('div').append(html);
it will become like this:
<div> <!-- children div of the current scope -->
<select>
<option value="10" selected>10</option>
<option value="20">20</option>
</select>
</div>
How is it possible?
edit: the variable contents is generated from remote locations, and I must change the value locally before it is being appended into a div. Hence, the question.
edit 2: sorry for the confusion, question has been updated with my real situation.
You can cast the HTML into a jQuery element and select the value at index 0. Then you can add it to the DOM.
Here is a simple jQuery plugin to select an option by index.
(function($) {
$.fn.selectOptionByIndex = function(index) {
this.find('option:eq(' + index + ')').prop('selected', true);
return this;
};
$.fn.selectOptionByValue = function(value) {
return this.val(value);
};
$.fn.selectOptionByText = function(text) {
this.find('option').each(function() {
$(this).attr('selected', $(this).text() == text);
});
return this;
};
})(jQuery);
var $html = $([
'<select>',
'<option value="10">10</option>',
'<option value="20">20</option>',
'</select>'
].join(''));
$('#select-handle').append($html.selectOptionByIndex(0));
// or
$html.selectOptionByValue(10);
// or
$html.selectOptionByText('10');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select-handle"></div>
By default, the first option will be selected - if you want to do on any other set it so using the index as soon as the select is appended:
$('#select_handle option:eq(1)').prop('selected', true)
(this selects the second option)
See demo below:
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20">20</option>'+
'</select>';
$('#select_handle').append(html);
$('#select_handle option:eq(1)').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="select_handle"></div>
You could try simply setting the value of the drop-down to the one you wish to 'select' - like
$("#select_handle select").val( a_value );
For example, if a_value is 30 it will add the needed HTML to the DOM node. This would be my take:
$(function() {
var html = '<select>' +
'<option value="10">10</option>' +
'<option value="20">20</option>' +
'<option value="30">30</option>' +
'<option value="40">40</option>' +
'<option value="50">50</option>' +
'</select>';
// set a value; must match a 'value' from the select or it will be ignored
var a_value = 30;
// append select HTML
$('#select_handle').append(html);
// set a value; must match a 'value' from the select or it will be ignored
$("#select_handle select").val(a_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>select added below</h2>
<div id="select_handle">
</div>
selected="selected" will work
var html = '<select>'+
'<option value="10">10</option>'+
'<option value="20" selected="selected">20</option>'+
'</select>';
$('#select_handle').append(html);
You can do this in jQuery using the .attr() function and nth pseudo-selector.
Like so:
$("option:nth-child(1)").attr("selected", "");
Hope it helps! :-)
after the append, try $('#select_handle select').val("10"); or 20 or whatever value you want to select
I want to copy the value inserted in a textbox to a select control, onclick of a button using javascript. I want to insert multiple values to get multiple options in the select.`
var temp1 = document.getElementById("textboxID").value.replace(/\s/g, "");
setSelectValue('selectID', temp1);
function setSelectValue (id, val) {
document.getElementById(id).value = val;}
This is my code and is not working. Thank you
`
Simple example (https://jsbin.com/sekihofihu/edit?html,output):
<input id="textboxID" />
<button onclick="addOption()">Copy</button>
<select id="selectID"></select>
<script>
var addOption = function()
{
var val = document.getElementById("textboxID").value.replace(/\s/g, "");
var select = document.getElementById('selectID');
var option = document.createElement("option");
option.text = val;
select.add(option);
}
</script>
If you want to add the content of the text input to your select as a new option you can use this:
var temp1 = document.getElementById("textboxID").value.replace(/\s/g, "");
setSelectValue('selectID', temp1);
function setSelectValue (id, val) {
document.getElementById(id).innerHTML += "<option value='" + val + "' >" + val + "</option>";}
Your question is not super clear but if you're trying to add an "option" element into a select element you can do something like this:
<html>
<body>
<select id="targetSelect" ></select>
<input id="sourceInput" type="Text" > </input>
<button id="submit" type="button" onclick="setSelectValue()">
Add to Select
</button>
<script>
function setSelectValue () {
var mySelectElement = document.getElementById("targetSelect");
var newOption = document.createElement("option");
newOption.text = document.getElementById("sourceInput").value;
mySelectElement.add(newOption,0);
}
</script>
</body>
</html>
I have been trying to figure out how to get all the input elements inside a div including select and textarea and pass them to editor, so far i figured out with input but i am just stuck with the rest.
Here is the code so far
function InsertShortcode(elem) {
var shortcodeName = elem.parentElement.id;
var inputs = document.getElementById(shortcodeName).getElementsByTagName('input'), i=0, e;
var inputs_val = '[' + shortcodeName;
while(e=inputs[i++]){
if(e.id){
inputs_val += ' ' + e.id + '="' + e.value + '"';
}
}
inputs_val += ']';
window.send_to_editor(inputs_val);
}
By this i am able to grab all the inputs inside a div where submit button is but still i am not sure how to grab textarea or select inputs.
The problem is that i have to make it dynamic. I will have many "shortcodes" and each will be in it's own div where the button is. But each will have it's own inputs which i can't control so i need to grab them all and send values to editor. Here's example of the code.
<div class="output-shortcodes">
<?php foreach( $theme_shortcodes as $key => $name ) { ?>
<div id="<?php echo $key ?>">
<p>
<h2><?php echo $name ?></h2>
</p>
<?php $form = $key . '_form';
if(function_exists($form)) {
$form(); // this is where the input fields are dynamically created on each shortcode.
}
?>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<?php } ?>
</div>
Use jQuery and the :input pseudo selector:
$('.output-shortcodes').find(':input');
That simple.
https://api.jquery.com/input-selector/
Or wrap it in a <form>, then you can use:
document.getElementById("outputForm").elements...
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
You can target your wrapper element and locate thru .find() all inputs within:
var inputs = $("#" + shortcodeName).find("select, textarea, input");
If you can use jQuery here is a fiddle: https://jsfiddle.net/q33hg0ar/
<div id="form">
<input type="text" name="input1" />
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<textarea name="notes"></textarea>
<button class="button-primary" onclick="InsertShortcode(this)">Insert shortcode</button>
</div>
<script>
$(document).ready(function() {
$('#form').find('input, select, textarea').each(function() {
console.log($(this).attr('name'));
});
});
</script>
And here it is w/o jQuery: https://jsfiddle.net/67pp3ggu/
window.onload = runIt();
function runIt() {
var elements = document.getElementById('form').childNodes;
var inputTypes = ['text', 'select-one', 'textarea'];
for (var i = 0; i < elements.length; i++) {
var elm = elements[i];
if (typeof elm.type !== 'undefined' && inputTypes.indexOf(elm.type)) {
console.log(elm);
console.log(elm.type);
}
}
}
At the end i switched to jQuery code completely and using :input helped me to resolve the problem.
Here is the complete code that i use now.
$('.vivid-framework-submit-shortcode').click(function(event) {
event.preventDefault();
var shortcodeName = $(this).closest('div').attr('id');
var inputs = $('#' + shortcodeName).find(':input');
var inputsVal = '[' + shortcodeName;
inputs.each(function() {
if($(this).attr('id') != 'content') {
inputsVal += ' ' + $(this).attr('id') + '="' + $(this).val() + '"';
console.log(inputsVal);
}
});
inputs.each(function() {
if($(this).attr('id') == 'content' ) {
inputsVal += ']' + $(this).val() + '[/' + shortcodeName;
}
});
inputsVal += ']';
window.send_to_editor(inputsVal);
});
What does it do? So now when i click on a button within shortcode div first using preventDefault to prevent page to scroll to top, next i grab the id of that div using it as shortcode name, and lastly i grab all the inputs and check if one of the inputs have id content because that will decide if shortcode is enclosed or selfclosed and loop through all inputs outputting their id's and values. and at the end return that to the editor.
Some of the terms may be unfamiliar but those who are familiar to WordPress will recognize terms like shortcode...
At the end final output is:
[bartag foo="value" bar="value"]content from textarea[/bartag]
If you downvote my questions or answers please explain why because i always tend to explain or ask as detailed as i can.
so below is my snippet. What I want is to create a select dropdown option base from the data attribute (data-select-text and data-select-values) of the currently clicked button, so below is a working snippet except for getting the data-select-values which is the problem because i dont know how to loop it along with the data-select-text so that the result of each select option will have values and text base from the split values of the data-select-text and data-select-values attribute, any ideas, help, suggestions, recommendations?
NOTE: currently, I could only able to use the attribute data-select-text as a select options values and text.
$(document).ready(function(){
$(document).on("click", "button", function(){
if($(this).attr("data-input-type").toLowerCase() === "select"){
var classList = $(this).attr('data-select-text').split(/\s+/);
var field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + item.replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
You could create an array for the values, the same as so did for the text.
Make sure that the order in both data-select-text and data-select-values is the same. Then you can use the index in your $.each loop:
$(document).ready(function(){
$(document).on("click", "button", function(){
var elem = $(this);
if( elem.attr("data-input-type").toLowerCase() === "select" ){
var classList = elem.data('select-text').split(/\s+/),
valueList = elem.data('select-values').split(/\s+/),
field = '<select>';
$.each(classList, function(index, item) {
field += '<option value="' + valueList[index].replace(/%/g, ' ') + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-input-type="select" data-select-text="select%1 select%2 select%3" data-select-values="1 2 3">Create a select dropdown option</button>
The result will be:
<select>
<option value="1">select 1</option>
<option value="2">select 2</option>
<option value="3">select 3</option>
</select>
Here is one way to do it, if I understand correctly. This code does not take into account different text or value lengths. It expects that the text length of options created is always equal to the values length being used.
$(document).ready(function () {
$(document).on("click", "button", function () {
if ($(this).attr("data-input-type").toLowerCase() === "select") {
var classList = $(this).attr('data-select-text').split(/\s+/);
var valueList = $(this).attr('data-select-values').split(' ');
var field = '<select>';
$.each(classList, function (index, item) {
field += '<option value="' + valueList[index] + '">' + item.replace(/%/g, ' ') + '</option>';
});
field += '</select>';
}
$("body").append(field);
})
});
Fiddle: http://jsfiddle.net/32qt0vn8/
I have variable in my java script which is global. Now i got different value each time when inner function call. I need to create a option tags with selected value as in attribute and one for without selected value based on the variable. I guess this is more confusing let me give you a example.
var a1 = "a1c" // default value but may change
if(a1 == "all")
{
var allstatusdefault = '<option value="all" selected="selected">All</option>';
}
else
{
var allstatusdefault = '<option value="all" >All</option>';
}
if(a1 == "a1b")
{
var allstatusdefault1 = '<option value="a1b" selected="selected">a1b</option>';
}
else
{
var allstatusdefault1 = '<option value="a1b" >a1b</option>';
}
if(a1 == "a1bc")
{
var allstatusdefault2 = '<option value="a1bc" selected="selected">a1bc</option>';
}
else
{
var allstatusdefault2 = '<option value="a1bc" >a1bc</option>';
}
This is just sample but i have to generate lot of option tag with different values.I don't want to write to many if ..anybody have any other idea?
Extract common code, I see a lot of duplication here.
var a1 = "a1c";
function buildOption(id) {
var selected = (a1 == id? ' selected="selected"' : '');
return '<option value="' + id + '"' + selected + '>' + id + '</option>';
}
var allstatusdefault = buildOption('all');
var allstatusdefault1 = buildOption('a1b');
var allstatusdefault2 = buildOption('a1bc');
From what i can deduct here is what you should do
var default1 = '<option value="'+a1+'" selected="selected">'+a1+'</option>';
var default2 = '<option value="'+a2+'" selected="selected">'+a2+'</option>';
Since the value of a1 is reused in the string, might as well just set it right away instead of using multiple if statements.
Note: when you have many if statement its the perfect opportunity to use a switch statement
For starters, learn about switch...case. In your case, it looks like you could possibly simply use the variable itself in the formation of the strings by concatenating the variable to a string.
var a1 = "a1bc" // default value but may change
switch(a1)
{
case "all" : allstatusdefault = '<option value="all" selected="selected">All</option>';break;
case "a1b" : allstatusdefault = '<option value="a1b" selected="selected">a1b</option>'; break;
case "a1bc" : allstatusdefault = '<option value="a1bc" selected="selected">a1bc</option>'; break;
default : allstatusdefault = '<option value="all" >All</option>';break;
}
window.alert(allstatusdefault);
I think from the way you are writing code you could do one with use jQuery. Create entire HTML first, with all the option values using jQuery object like this :
var $optionHTML = $('<option value=""> Blahblah </option>');
Now you can apply all jquery function to this guy. so you append a new option like this.
$optionHTML.append('<option>...</option>')
when you are done with all the option element use jquery selector method to find an element with option having value attribute matching to a1c then add attribute selected then you are done.
Do let me know if you need some code for starters.
Thanks.
EDIT :
HERE IS THE ANSWER
<html>
<head>
<script type = "text/javascript" src= "http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type = "text/javascript">
$(document).ready (function () {
var value = "test 2";
$select = $("<select></select>");
$optionHTML1 = $('<option value="test 1">Test 1</option>');
$optionHTML2 = $('<option value="test 2">Test 2</option>');
$optionHTML1.appendTo($select);
$optionHTML2.appendTo($select);
$select.find("[value='test 2']").attr('selected','selected');
alert($select.html());
$("div").append($select);
});
</script>
<style type = "text/css">
</style>
</head>
<body>
<div>
</div>
</body>