JS insertHtml without focus? - javascript

I have some code written in PHP with textarea input field. I also have a JS code that inserts html code into field:
$('form textarea#response').ready(function() {
function populateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0, len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
var test = populateGet();
var ticid;
for(var key in test) {
if(Object.prototype.hasOwnProperty.call(test, key)) {
var val = test[key];
ticid = val;
}
}
$('form select#cannedResp').val('original');
var fObj = $(this).closest('form');
var $url = 'ajax.php/tickets/'+ticid+'/canned-resp/original.json';
$.ajax({
type: "GET",
url: $url,
dataType: 'json',
cache: false,
success: function(canned){
console.log('dupa');
//Canned response.
var box = $('form textarea#response'),
redactor = box.data('redactor');
if(canned.response) {
if (redactor){
redactor.insertHtml(canned.response);
}else{
box.val(box.val() + canned.response);
box.blur();
}
//if (redactor)
//redactor.observeStart();
}
//Canned attachments.
var ca = $('.attachments', fObj);
if(canned.files && ca.length) {
var fdb = ca.find('.dropzone').data('dropbox');
$.each(canned.files,function(i, j) {
fdb.addNode(j);
});
}
document.getElementById('focustest').focus();
}
})
.done(function() { })
.fail(function() { });
});
The problem is that execution of above code (redactor.insertHtml(canned.response);) causes focus on the textarea. The code is executed on page load.
Is there any way I can insert the content into field without causing the focus to placed on this field?
Thank you in advance and best regards
Tom

Related

How to get selected row values from a table

I am converting a HTML table to an array and passing it in to a controller for inserting multiple rows. I am able to create the array, but the problem is it's creating a complete table array but I want to get the selected row td values only.
//function to convert HTML table to array//
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}
$(document).on('click', '#btnsave', function() {
var data = HTMLtbl.getData($('#tblresult'));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Home/Save_SearchCarsDocs",
data: JSON.stringify(parameters)
});
request.done(function(msg) {
alert("Row saved " + msg.d);
});
You can try following...
//function to convert HTML table to array//
var excludedTD_Index = [0,5,7]; // define what you want to exclude by index
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
if(excludedTD_Index.indexOf(colIndex) >=0) // exclude TD
continue;
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}
$(document).on('click', '#btnsave', function() {
var data = HTMLtbl.getData($('#tblresult'));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Home/Save_SearchCarsDocs",
data: JSON.stringify(parameters)
});
request.done(function(msg) {
alert("Row saved " + msg.d);
});
OR you can make it more managable if you can add following data to your TD tag
<td data-exclude="1">
...
after adding above data you can exclude those columns as following
var HTMLtbl = {
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function(rowIndex, r) {
var cols = [];
// I believe the main problem is here:
$(this).find('td').each(function(colIndex, c) {
if($(this).data("exclude") == 1) // exclude TD
continue;
cols.push($(this).text().trim());
});
data.push(cols);
});
return data;
}
}
thanks Rory McCrossan finally get my answer i am adding my solution below
var CB=1;
var HTMLtbl =
{
getData: function (table) {
var data = [];
table.find('tr').not(':first').each(function (rowIndex, r) {
if ($("#chk_" + CB).is(':checked'))
{
var cols = [];
$(this).find('td').each(function (colIndex, c) {
cols.push($(this).text().trim());
});
data.push(cols);
}
CB++;
});
CB = 1;
return data;
}
}

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

post data using ajax and js

Every time i try to use my classes below to post the array i made (also below) the ajax request doesn't pass the input as $_POST values but as $_REQUEST values seen in the web address bar at the top of the screen. I'm very new to Ajax and javascript (only been working with it about a month) so any tips and trick to fix anything below is greatly appreciated.
var formErrors=["Passage","FirstName","Zip"];
var formInput=["EventID","Passage","FirstName","LastName","Email","Organization","Location","Zip"];
Head of HTML
$(function () {
$("#signUp").click(function() {
if(formArrayValidation(formErrors) != false) {
formPostAjax(formInput, 'join-event.php');
}
return false;
});
});
Basics.js
formArrayValidation = function(errorArray) {
for(var i = 0; i < errorArray.length; i++) {
$('.error').hide();
var name = $("input#" + errorArray[i]).val();
if (name == "") {
$("label#" + errorArray[i] + "_error").show();
$("input#" + errorArray[i]).focus();
return false;
}
}
}
formPostAjax = function(inputArray, form) {
var dataString = "";
for(var i = 0; i < inputArray.length; i++)
{
var data = inputArray[i];
var dataInput = $("input#" + data).val();
if(i = 0) {
dataString = dataString + data + '=' + dataInput;
}
else {
dataString = dataString + '&' + data + '=' + dataInput;
}
}
$.ajax ({
type: "POST",
url: form,
data: dataString,
success: function() {
}
});
}
Your event listener should be on the form and it should be:
$('#form_identifier').submit(...);
Additionally, jQuery provides a nice shortcut method for serializing form data:
$('#form_identifier').submit(function(){
var post_data = $(this).serialize()
// ....
return false;
});

fuzzy search (fuse.js) using XML instead of JSON

Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});

Url.Action Passing string array from View to Controller in MVC#

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action.Currently I can't pass my parameters. I am new in MVC3.
Pls let me know why I can't pass parameter to ActionResult..I already define ActionResult with Same parameter name..
thanks all in advance....
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
var columnNames = "";
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
});
Try this,
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
// columnNames is an object now
var columnNames = {};
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames[i] = $("#grid")[0].p.colModel[i].name;
}
}
var Val1 = jQuery(txt_search1).val();
document.location = "Home/Index/" + $.param({ Val1 = Val1 , columnNames = columnNames });
});
Your action that takes columnNames as a string array
public ActionResult Index(string val1, string[] columnNames)
{
// Your code
}
UPDATE:
If the URL becomes too big you can submit the values through form using POST method. If your view already have a form use that else create a dynamic one on the fly and submit the values through POST.
$('#export-button').click(function () {
var Val1 = jQuery(txt_search1).val();
$("#hidden-form").remove();
// create a form dynamically
var form = $('<form>')
.attr({ id: "hidden-form",
action: "/Home/Index",
method: "post",
style: "display: none;"
})
.appendTo("body");
// add the "Val1" as hidden field to the form.
$('<input>').attr({ name: "Val1 ", value: Val1, type: "hidden" }).appendTo(form);
var columnLength = $("#grid")[0].p.colNames.length;
// add the "columnNames" as hidden fields to the form
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
var t = $("#grid")[0].p.colModel[i].name;
$('<input>').attr({ name: "columnNames", value: t, type: "hidden"
}).appendTo(form);
}
};
// submit the form
form.submit();
});
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
Hi Louis,
Your are trying to access javascript varaibles Val1 and columnNames from the server side tag and it is not possible. For more details, please refer this URL.
You can do it by following way.
var jsonData = { val1 : Val1, columnNames : columnNames };
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: "Home/Index", // Location of the service
data: jsonData,
contentType: "application/json; charset=utf-8", // content type sent to server
processdata: true, //True or False
success: function () {
alert("success")
}
});
On your controller side you have to write like
public ActionResult Index(string val1, string columnNames)
{
// Your code
}
You tagged JQuery-Ajax but i don't see any ajax attempt in the code example? So i am guessing you want to know an Ajax orientated solution. You're probably not using Zend Framework, but i hope this answers helps point you in the right direction to a solution.
From JS/Zend framework experience you could look at something like
$('#export-button').click(function () {
....
var actionUrl= "/controller/action/";
$.ajax({
url: actionUrl,
data: {
variable1: "OrgDataExport",
variable2: "Search",
Val1: Val1,
columnNames: columnNames
},
dataType: "json",
success: function(json) {
//do stuff
}
});
....
});
In the ZendFramework controller you can then grab the variables on the request:
$Val1 = $this->_request->getparam("Val1");

Categories

Resources