I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
Related
I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
I have made an AJAX request that fetches completed Ebay auction results using Ebay's API (Finding Service). It works, producing the desired results, but now I am a stuck on how best to filter those results (in my case, using a button) by price, date of sale, etc.
For example: I have the variable url which has the filter url += "&sortOrder=StartTimeNewest";. I would like a button to toggle between that filter and url += "&sortOrder=StartTimeOldest"; using a click event.
I am a student, and pretty inexperienced when it comes to JS/frameworks...and so far have not had much luck figuring out the best way to do this aside from duplicating my entire code from ebay.js and altering it slightly for each filter I would like to apply.
For example: I can create different variables like url1, url2 and so on that have the filters I want, calling them from a different ajax requests attached to the buttons...
...but I'm sure there is a better and simpler way to do this without being so repetitive and would appreciate any help pointing me in the right direction.
Ebay.js
$(window).load(function() {
$('form[role="search"]').submit(function(ev) {
ev.preventDefault();
var searchstring = $('input[type="text"]', this).val();
var url = "https://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findCompletedItems";
url += "&SERVICE-VERSION=1.13.0";
url += "&SERVICE-NAME=FindingService";
url += "&SECURITY-APPNAME=BrandonE-DigIt-PRD-5cd429718-3d6a116b";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&REST-PAYLOAD";
url += "&itemFilter(0).name=MinPrice";
url += "&itemFilter(0).value=7.00";
url += "&itemFilter(0).paramName=Currency";
url += "&itemFilter(0).paramValue=USD";
url += "&paginationInput.pageNumber=1";
url += "&paginationInput.entriesPerPage=50";
url += "&keywords=" + searchstring;
url += "&sortOrder=StartTimeNewest";
url += "&categoryId=176985";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function(res){
console.log(res);
var items = res.findCompletedItemsResponse[0].searchResult[0].item;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "<img src='" + items[i].galleryURL + " '/>";
ins += " " + items[i].title + " - ";
ins += "Sold for $" + items[i].sellingStatus[0].currentPrice[0].__value__;
ins += "</div><br />";
};
$('.results').html(ins);
}
});
});
});
HTML:
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button id="mainbtn" type="submit" class="btn btn-default">Search</button>
</form>
<div class="filters col-xs-12 col-md-10 col-offset-md-1">
<!-- TOGGLE BUTTONS WILL ALLOW RESULTS TO BE SORTED. -->
<button type="button" class="btn btn-info btn-sm date-btn">date</button>
<button type="button" class="btn btn-info btn-sm price-btn">price</button>
</div>
<br />
<div class="index col-xs-12 col-md-10 col-offset-md-1">
<p class="restitle">results:</p><br />
<div class="results"></div>
</div>
Per our comments, I created a simple class that will generate the url for you.
Go ahead and tweek it to get the correct values in there. Hopefully this helps!
I added comments in the code but lmk if you have any questions.
$(function() {
// invoke click event
$("[data-filter]").off();
$("[data-filter]").on("click", function() {
let $this = $(this);
let data = $this.data();
// toggle value
if (data.value == false) {
$(this).data("value", true);
} else {
$(this).data("value", false);
}
// create class
let url = new buildfindCompletedItemsUrl();
// get the sort order
url.getSortOrder();
// build the url
let ajaxUrl = url.build();
// get the results
GetFilteredResults(ajaxUrl, function(results) {
$("body").append($("<p />", {
text: results
}));
})
});
})
// class with contructor
function buildfindCompletedItemsUrl() {
this.url = "https://svcs.ebay.com/services/search/FindingService/v1";
this.defaultUrlParams = {
"OPERATION-NAME": "findCompletedItems",
"SERVICE-VERSION": "1.13.0",
"SERVICE-NAME": "FindingService",
"SECURITY-APPNAME": "BrandonE-DigIt-PRD-5cd429718-3d6a116b",
"GLOBAL-ID": "EBAY-US",
"RESPONSE-DATA-FORMAT": "JSON",
"REST-PAYLOAD": "",
"itemFilter(0).name": "MinPrice",
"itemFilter(0).value": "7.00",
"itemFilter(0).paramName": "Currency",
"itemFilter(0).paramValue": "USD",
"paginationInput.pageNumber": "1",
"sortOrder": "",
"paginationInput.entriesPerPage": "50",
"categoryId": "176985"
}
return this;
}
// looks at the dom and fills the sortOrderParam
buildfindCompletedItemsUrl.prototype.getSortOrder = function() {
var $filters = $("[data-filter]");
let param = this.defaultUrlParams["sortOrder"];
let _ = this;
$.each($filters, function(i, f) {
let $filter = $(f);
let data = $filter.data();
let val = data.value;
if (val == true) {
if (_.defaultUrlParams["sortOrder"] == "") {
_.defaultUrlParams["sortOrder"] += data.filter;
} else {
_.defaultUrlParams["sortOrder"] += "," + data.filter;
}
}
})
};
// builds the full url for the ajax call
buildfindCompletedItemsUrl.prototype.build = function() {
let _url = this.url;
let keys = Object.keys(this.defaultUrlParams);
let length = keys.length;
for (let i = 0; i < length; i++) {
let key = keys[i];
let val = this.defaultUrlParams[key];
if (i == 0) {
_url += `?${key}=${val}`;
} else {
_url += `&${key}=${val}`;
}
}
return _url;
}
// get your results and return them
function GetFilteredResults(url, callback) {
// do ajax here
return callback(url)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-filter="date" data-value="false">Sort By Date</button>
<button data-filter="price" data-value="false">Sort By Price</button>
I have the following script. After a user clicks submits I want to redirect the user to the same page and populate the drop down and input box with parameter values from the url. Unfortunately they are not populating once the redirect completes. I also need to strip off * from the FilterMultiValue parameter so that the textbox has the orginal value entered?
I've checked the parameter values using an alert function and that works?
<script type="text/javascript">
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
function RedirectUrl() {
var tb = document.getElementById("tbSearch").value;
var cs = document.getElementById("sfield").value;
var url = "";
if (tb != "") {
url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
window.location.href = "mypage.aspx?" + url;
var params = getUrlParams();
alert(params.FilterName);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = params.FilterMultiValue;
}
else {
return false;
}
}
function ClearUrl() {
window.location.href = "mypage.aspx";
document.getElementById("sfield").value = "";
document.getElementById('tbSearch').value = "";
}
</script>
Search Field:
<select id="sfield">
<option selected value="Title" >Title</option>
<option value="Body">Body</option>
</select>
Search Text:
<input type="text" id="tbSearch" />
<input type="button" id="btnSearch" value="Search" onclick="return RedirectUrl();" />
<input type="button" id="btnClear" value="Clear" onclick="return ClearUrl();" />
window.location.href = "mypage.aspx?" + url;
reloads the page, which will result in all code after that not beeing executed.
What you want to do is to add code for pageload and check if the parameters are given, then populate the textbox.
Something like:
window.addEventListener('load', function(){
var params = getUrlParams();
if(typeof params.FilterName !== 'undefined'){
// removes the first and the last char from the string
var t = params.FilterMultiValue.substr(1, params.FilterMultiValue.length-2);
document.getElementById("sfield").value = params.FilterName;
document.getElementById('tbSearch').value = t;
}
});
I am trying to add and remove dropdown <select>s to a form on a button click. This is the code I have currently. I could have sworn I had this working last night, but when I went to work some more on my project this morning, the dropdowns wouldn't add / remove correctly.
function DropDowns(){
this.counter = 0;
this.addDropdown = function (divname) {
var newDiv = document.createElement('div');
var html = '<select name="cookie' + this.counter + '">', i;
for (i = 0; i < cookies_drop.length; i++) {
html += "<option value='" + cookies_drop[i] + "'>" + cookies_drop[i] + "</option>"
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
this.counter++;
}
this.remDropdown = function() {
$('#dropdowns-container').find('div:last').remove();
this.counter--;
}
}
var dropsTest = new DropDowns();
HTML:
<form action='' method=post id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I can only figure out the main problem may be on the server side when you create the cookies_drop variable using json_encode.
Other problems may reside in:
A test on the parameter of addDropdown function is suggested to check if it's valid
In the function remDropdown the decrement of the counter variable must be done only if the element is actually removed
You mixed jQuery and javaScript
Instead of using directly the createElement, making the code more simple and readable, you used the innerHTML property.
So, my snippet is:
// I assume you used something like:
// var cookies_drop = JSON.parse( '<?php echo json_encode($data) ?>' );
var cookies_drop = [{text: "Text1", val: "Value1"},
{text: "Text2", val: "Value2"},
{text: "Text3", val: "Value3"}];
function DropDowns() {
this.counter = 0;
this.addDropdown = function (divname) {
var divEle = document.querySelectorAll('form[id=' + divname + ']');
if (divEle.length != 1) {
return; // error
}
var newDiv = document.createElement('div');
var newSelect = document.createElement('select');
newSelect.name = 'cookie' + this.counter;
newDiv.appendChild(newSelect);
for (var i = 0; i < cookies_drop.length; i++) {
var newOption = document.createElement('option');
newOption.value = cookies_drop[i].val;
newOption.text = cookies_drop[i].text;
newSelect.appendChild(newOption);
}
divEle[0].appendChild(newDiv);
this.counter++;
}
this.remDropdown = function () {
var lastDiv = document.querySelectorAll('#dropdowns-container div:last-child');
if (lastDiv.length == 1) {
lastDiv[0].parentNode.removeChild(lastDiv[0]);
this.counter--;
}
}
}
var dropsTest = new DropDowns();
<form action="" method="post" id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I am doing this by taking the cursor position from the content-editable box. When a new tag is created the cursor comes before the tag but it should be after the tag. Also i am not able to merge/split the tag.
Please give some idea how can i do this.
Visit (https://plnkr.co/edit/DSHKEcOnBXi54KyiMpaT?p=preview) !
What i want here, after pressing the enter key for new tag the cursor should be at the end of tag while it is not and also the merging/spliting functionality like the twitter what's happening box.
Thanks in advance.
Now this code is working fr me
$scope.myIndexValue = "5";
$scope.searchTag = function(term) {
var tagList = [];
angular.forEach($rootScope.tags, function(item) {
if (item.name.toUpperCase().indexOf(term.toUpperCase()) >= 0) {
tagList.push(item);
}
});
$scope.tag = tagList;
return $q.when(tagList);
};
$scope.getTagText = function(item) {
// note item.label is sent when the typedText wasn't found
return '<a>#<i>' + (item.name || item.label) + '</i></a> ';
};
$scope.resetDemo = function() {
// finally enter content that will raise a menu after everything is set up
$timeout(function() {
//var html = "Tell us something about this or add a macro like brb, omw, (smile)";
var htmlContent = $element.find('#htmlContent');
var html = "";
if (htmlContent) {
var ngHtmlContent = angular.element(htmlContent);
ngHtmlContent.html(html);
ngHtmlContent.scope().htmlContent = html;
// select right after the #
mentioUtil.selectElement(null, htmlContent, [0], 8);
ngHtmlContent.scope().$apply();
}
}, 0);
};
HTML :
<div class="share_tags fs-12">
<div class="row margin_row">
<div class="col-md-12 no_padding">
<div class="form-group">
<div contenteditable="true" mentio
mentio-typed-term="typedTerm"
mentio-macros="macros"
mentio-require-leading-space="true"
mentio-select-not-found="true"
class="editor tag" placeholder="Tell Us something about This"
mentio-id="'htmlContent'"
id="htmlContent"
ng-model="htmlContent">
</div>
</div>
<mentio-menu
mentio-for="'htmlContent'"
mentio-trigger-char="'#'"
mentio-items="tag"
mentio-template-url="/people-mentions.tpl"
mentio-search="searchTag(term)"
mentio-select="getTagText(item)"
></mentio-menu>
</div>
</div>
<script type="text/ng-template" id="/people-mentions.tpl">
<ul class="list-group user-search">
<li mentio-menu-item="tag" ng-repeat="tag in items" class="list-group-item">
<span ng-bind-html="tag.name | mentioHighlight:typedTerm:'menu-highlighted' | unsafe"></span>
</li>
</ul>
</script>
</div>
Reference link
http://jeff-collins.github.io/ment.io/?utm_source=angular-js.in&utm_medium=website&utm_campaign=content-curation#/
is working fine for me.
This is not working perfectly but for the time being i am using this code.
In app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $filter, $element) {
var tags;
$scope.allTags = ['Tag1', 'PrivateTag', 'Xtag', 'PublicTag1', 'newTag', 'socialTag', 'cricketTag'];
var replacedTag = '';
var replacedIndex;
var data;
$scope.log = function (name) {
$scope.tags = [];
$('ul').html(' ');
console.log("here", $('ul'))
var data = $('textarea').val();
replacedIndex = data.indexOf(replacedTag)
console.log('test', name, replacedTag, replacedIndex, data);
var replacedData = data.substring(0, replacedIndex - 1) + ' #' + name + data.substr(replacedIndex + replacedTag.length);
$('textarea').val(replacedData);
$('textarea').keyup();
}
f = $scope.log;
$('textarea').on('keyup', function (e) {
function getIndexOf(arr, val) {
var l = arr.length,
k = 0;
for (k = 0; k < l; k = k + 1) {
if (arr[k] === val) {
return k;
}
}
return false;
}
$('ul').html('');
$scope.tags = [];
tags = $(this).val().match(/#\S+/g);
console.log("---tags-", tags)
var a = data = $(this).val();
if (tags && tags.length) {
tags.forEach(function (tag,index) {
var index1 = getIndexOf(tags, tag);
console.log("index----",index, index1,tag)
replacedTag = tag;
$scope.tags = tag ? $filter('filter')($scope.allTags, tag.substr(1)) : [];
if ($scope.tags && $scope.tags.length && (e.keyCode && e.keCode != 32)) {
$scope.tags.forEach(function (tag1, index) {
$('ul').append('<li>' + '<a href="javascript:;" onclick=f("' + tag1 + '");>'
+ tag1 + '</a>' + '</li>')
})
}
else {
$('ul').html(' ');
}
if(index == index1) {
var b = a.substring(0, a.indexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.indexOf(tag) + tag.length);
}
else {
var b = a.substring(0, a.lastIndexOf(tag) - 1) + ' <a>' + tag + '</a> ' + a.substr(a.lastIndexOf(tag) + tag.length);
}
a = b;
$('p').html(b)
})
}
})
});
HTML
<br>
<br>
<p></p>
<textarea rows="2" cols="80"></textarea>
<div>
<ul>
</ul>
</div>
For live demo Visit
https://plnkr.co/edit/SD9eouQa5yrViwxQD6yN?p=preview
i am also looking for the better answer.
I assume you're talking about gathering hash tags from a string of sorts, the snippet below demonstrates how you can build an array of #hashed tags without modifying the cursor position.
It uses a simple regular expression to match tags found in the textarea and then pushes them to an array.
var tags;
$('textarea').on('keyup', function(){
tags = $(this).val().match(/#\S+/g)
$('ul').html('');
tags.forEach(function(tag){
$('ul').append('<li>' + tag + '</li>')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<ul></ul>