I am using jquery chosen and calling ajax on change drop down but records are not displaying. This code which I am using after changing drop down.
$.ajax({
type: "POST",
url: "MY URL",
data: {
sno: $(this).val()
},
success: function (resp) {
var resp = jQuery.parseJSON(resp);
if (resp.length == 0) {
$("#site").html('<option value="0" selected>Select Site</option>');
} else {
$.each(resp, function (i, item) {
$('#site').append($('<option>', {
value: item.siteNameID + '-' + item.siteName,
text: item.siteName
}));
});
}
},
error: function (resp) {
console.log('error');
}
});
One thing I have noticed jquery chosen applying on my select box but data which I am fetching from server side is not adding in that select box
You will need to call the chosen update trigger after you add items to your select list dynamically in order for them to show up. Use the following line after you have appended items and they should be displayed in your list.
$('#site').trigger("chosen:updated");
I think my code is not the answer for your question, but this mimics adding options to select... just click the add button...
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="add()">Add</button>
<select id="select"></select>
<script>
var json = [{title:"lorem",value:1},
{title:"john doe",value:2},
{title:"foo",value:3},
];
function add(){
$("#select").empty();
for(var x = 0; x<json.length; x++){
var option = '<option value="'+json[x].value+'"> '+json[x].value+'-'+json[x].title+'</option>';
$("#select").append($(option));
}
}
</script>
</body>
</html>
Related
Hi I'm working on script that I got in this forum.
Options are mentioned in the column A and Links are added in Column B, in the dropdown If I click the option 1 I want to open the respective link which is in Column B in another tab.
Code.gs
function doGet(e) {
return HtmlService.createTemplateFromFile("Index.html")
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function getSelectOptions()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Options');
var rg=sh.getDataRange();
var vA=rg.getValues();
var options=[];
for(var i=0;i<vA.length;i++)
{
options.push(vA[i][0]);
}
return vA;
}
function showSidebar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('Index');
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'The Drop Down with No Options now has options.');
}
Index.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(vA)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
console.log("My code");
</script>
</head>
<body>
<select id="sel1" style="width:125px;height:35px;margin:10px 0 10px 0;">
</select>
</body>
</html>
I couldn't figure it out how to embed the link into option. should another function defined for individual column or can it be done in single function?
Note: I'm not a coder.
You can use the onChange event to open the link when a user chooses an option
For this:
Use the syntax new Option(text, value). To pass the option and the link as the text and the value, you need to access the respective nested array elements:
select.options[i] = new Option(vA[i][0],vA[i][1]);
Use the method window.open() to open the link
Build an event handler function that accesses the selected value onChange with document.getElementById("sel1").value
Sample:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(vA)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i][0],vA[i][1]);
}
}
console.log("My code");
function myFunction(){
var value = document.getElementById("sel1").value;
window.open(value, '_blank');
}
</script>
</head>
<body>
<select id="sel1" style="width:125px;height:35px;margin:10px 0 10px 0;" onchange="myFunction()">
</select>
</body>
</html>
There are two steps on my code. First step a user fills some fields and then data is submitted by ajax to server. Ajax returns a HTML select input that user must choose a value. This is the second step.
The problem is, when I try to get the value of select in javascript, it shows me null.
The code I use to get select value works in normal situation. But when select is retrieved by ajax, this problem occurs.
Code to get select value
var e = document.getElementById("ordernum");
var num = e.options[e.selectedIndex].value;
Here's an example HTML file showing how to dynamically generate a select element and get the value back from it on its onchange event via event.target.value:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
const GameDifficulty = {
EASY:1,
MEDIUM:2,
HARD:3,
INSANE:4
};
function init(event) {
console.log(event);
var body = document.getElementById('body');
var select = document.createElement('select');
select.id = 'selDifficulty';
for (var diff in GameDifficulty) {
var option = document.createElement('option');
option.value = GameDifficulty[diff];
option.innerHTML = diff;
select.appendChild(option);
}
select.onchange = test;
body.appendChild(select);
console.log(body);
}
function test(event) {
console.log(event.target.value);
}
window.onload = init;
</script>
</head>
<body id="body">
</body>
</html>
I'm loading a table dynamically using jQuery ajax, the rows of the table has "contenteditable=true", I'm trying to listen on blur event for every cell, so that it triggers a function to update that cell dynamically.
The problem is that the event blur isn't fired at all, I've tried different selectors(table,tbody, and finally the whole document), but all in vain.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src='jquery-1.8.3.js'></script>
<link rel="stylesheet" href='jquery-ui-1.8.7.custom.css' type="text/css">
<?php
include './datatable_include.php';
?>
<script type="text/javascript">
$(function () {
$.ajax({//create an ajax request to load_page.php
type: "GET",
url: "load_table.php",
dataType: "html", //expect html to be returned
success: function (response) {
$('#dataTable').find('tbody').html(response);
initDataTable('#dataTable', null);
}
});
});
$(document).bind("blur", "td", (function () {
// this code isn't reached
alert("ahoo");
var id = $(this).attr("id");
var name = $(this).attr("name");
var message_status = $("#status");
var value = $(this).text();
$.post('update_table.php', "id=" + id + "&" + name + "=" + value, function (data) {
if (data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function () {
message_status.hide()
}, 3000);
}
});
}));
</script>
</head>
<body>
<table id="dataTable" width="700px" >
<thead>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
try
$(document).bind("td").blur(function()
{
});
seems that table td isn't a standard focusable element so you can't blur it.
try to add the tabsindex property to each td
<td tabindex="1">focus on me</td>
the definition of bind function is as follows:
.bind( eventType [, eventData ], handler )
so, you should do:
$('td').bind('blur', function(){
//event handler statement goes here
});
And as mentioned by #paul roub in the comments above, you should be using live() function, as you are creating the td elements dynamically.
$('td').live('blur', function(){
//event handler statement goes here
});
I am trying to bind a function to the select field when something is pasted into it (it looks like an input field after allowing multiple style and select2:matcher/tokenize) but in IE it always truncates any pasted text which contains a new line character.
<form method="POST" action="/run" class="ui-widget" onsubmit=" return confirmSubmit(this, 'run',true) ">
Editor:
<select name="editor" id="editor" multiple style="width: 200px">
<option>ALL</option>
</select>
<input type="submit" value="Submit">
</form>
bind('paste') does not seem to work on an <select> object so I had to use bind('change')
var unitIds = ["Red","Yellow","Green"];
$.each(unitIds, function(i, f) {
$('select[name="editor"]').append($('<option>').text(f));
});
$('#pastefromclip').select2({
matcher: function(term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) === 0;
},
tokenizer: function(input, selection, callback) {
if (input.indexOf(" ") < 0) return;
var parts = input.split(" ");
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if(part.length > 0){
if (unitIds.indexOf(part) == -1) {
alert('Invalid fields: ' + part);
} else {
callback({
id: part,
text: part
});
}
}
}
}
});
$('#editor').bind('change', function (e) {
var clipped = window.clipboardData.getData('Text');
clipped = clipped.replace(/(\r\n|\n|\r)/gm, " "); //replace newlines with spaces
//$(this).val(clipped); // this doesn't seem to work
var element = document.getElementById('editor');
element.value = clipped; // doesn't seem to work either
return false; //cancel the pasting event
});
Copy and paste the following into the select field:
Red
Yellow
It pastes only 'Red' and shows the matched object. It does not recognise the change function until I select that matched object and it is being tokenized.
After it recognises that change, it runs through the clipboardData and sees both Red and Yellow but it cannot assign the select field with that data.
<script src="https://rawgit.com/free-jqgrid/jqGrid/master/plugins/jquery.jqgrid.showhidecolumnmenu.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery-1.8.3.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery-ui-1.9.2.js"></script>
<script type="text/javascript" src="javascript/toastr.min.js"></script>
<script type="text/javascript" src="javascript/adminConsole.js"></script>
<script type="text/javascript" src="javascript/select2.min.js"></script>
<script type="text/javascript" src="javascript/moment.min.js"></script>
<script type="text/javascript" src="javascript/jqGrid/ui.multiselect.js"></script>
<script type="text/javascript" src="javascript/jqGrid/grid.locale-en.js"></script>
<script type="text/javascript" src="javascript/jqGrid/jquery.jqGrid.min.js"></script>
use TokenSeparators for multiple inputs
See it Action
$(".js-example-tokenizer").select2({
tags: true,
tokenSeparators: [',', ' ']
})
Please refer the section Automatic tokenization in Select2 Tokenization
Also when Copy paste the options (Red Green ) don't forget to append "," at last
I am trying to learn to use Knockoutjs but I am facing a problem
this is the scenario:
I have a page where I define a Knockoutjs viewModel as follow
$(document).ready(function () {
var viewModel = {
selectedColumns: ko.observableArray()
};
ko.applyBindings(viewModel);
});
Now with an Ajax request I add to the page a checkbox which I want to bind to the viewModel
<input type='checkbox' id='someId' data-bind='attr: { value: 'someValue' }, checked: $root.selectedColumns'>
$(document).ready(function() {
ko.applyBindings(viewModel, document.getElementById(someId));
});
but I always get
Error: ReferenceError: viewModel is not defined
Source File: http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
I've created a test page where everything is on one page and it works
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src="../../Scripts/knockout-2.1.0.debug.js" type="text/javascript"></script>
<script type="text/javascript">
var count = 0;
var viewModel = {
selectedPeople: ko.observableArray()
};
$(document).ready(function () {
ko.applyBindings(viewModel);
});
function AddAnotherCheckbox(){
var id = "checkbox" + count;
var checknox = count + " <input type='checkbox' id='" + id + "' data-bind='attr: { value: \"" + count + "\" }, checked: $root.selectedPeople'><br/>";
$("#container").append(checknox);
count++;
$(document).ready(function() {
ko.applyBindings(viewModel, document.getElementById(id));
});
}
</script>
</head>
<body>
<input type="button" onclick="AddAnotherCheckbox()"/>
<div id="container"></div>
<br/>
<br/>
<br/>
<span data-bind="text: selectedPeople"></span>
</body>
</html>
But I can't make it working using partial view
Could you explain to me what's the problem and how can I solve it?
thanks
Description
This is not about Knockout, it's about JavaScript in general.
Your Testcode works because you have defined the viewModel outside of $(document).ready
This is a other scope.
Compare theese to jsFiddles
This does not work (your scenario)
This works
Sample
This does not work
$(document).ready(function () {
var viewModel = {
someThing : "Test"
};
});
$(document).ready(function () {
alert(viewModel.someThing);
});
This will work
var viewModel;
$(document).ready(function () {
viewModel = {
someThing : "Test"
};
});
$(document).ready(function () {
alert(viewModel.someThing);
});
More Information
Explaining JavaScript Scope And Closures