This question already has answers here:
Trim string in JavaScript
(20 answers)
Closed 8 years ago.
function ShowEditBox(serial)
{
$("#divEditBox").slideDown("medium");
var pserial ='PName'+ serial;
var colindex = 0;
var $tr = $("#" + pserial).parent().parent();
$tr.find('td').each(function () {
if (colindex == 2) {
$("#txtName").val($(this).text());
} else if (colindex == 3) {
$("#txtSurName").val($(this).text());
} else if (colindex == 4) {
$("#txtEmail").val($(this).text());
} else if (colindex == 5) {
$("#txtMobile").val($(this).text());
} else if (colindex == 6) {
$("#txtAddress").val($(this).text());
}
colindex++;
})
$("#hdField").val(serial);
}
Whenever i click the edit button in grid view that particular row data should be displayed in text boxes. But here i am getting unnecessary spaces in text boxes.
How can i trim the spaces in the Text box(txtName) ?? I am getting spaces in text .
Try to use $.trim("string"),
$("#txtName").val($.trim($(this).text()));
use trim() function of javascript
for jquery look at here Trim
Look at here
example
var str = " lots of spaces before and after ";
$( "#original" ).html( "Original String: '" + str + "'" );
$( "#trimmed" ).html( "$.trim()'ed: '" + $.trim(str) + "'" );
Use javascript trim() method.
$("#txtName").val($(this).text().trim());
function ShowEditBox(serial)
{
$("#divEditBox").slideDown("medium");
var pserial ='PName'+ serial;
var colindex = 0;
var $tr = $("#" + pserial).parent().parent();
$tr.find('td').each(function () {
if (colindex == 2) {
$("#txtName").val($.trim($(this).text()));
} else if (colindex == 3) {
$("#txtSurName").val($.trim($(this).text()));
} else if (colindex == 4) {
$("#txtEmail").val($.trim($(this).text()));
} else if (colindex == 5) {
$("#txtMobile").val($.trim($(this).text()));
} else if (colindex == 6) {
$("#txtAddress").val($.trim($(this).text()));
}
colindex++;
})
$("#hdField").val(serial);
}
Related
my javascript file for multiple email(multiple_emails.js plugin) is working fine with ng serve my code :
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top",
invalid:"Invalid Email Id"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
var to_id = this.id;
var orig_id=to_id;
console.log(to_id);
var arr = to_id.split('_');
to_id = arr[1];
console.log("to_id",to_id);
setTimeout(function(){
console.log($('.licls'+to_id).length);
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
},200);
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" id=ul_'+to_id+' />'); // create html elements - list of email addresses as unordered list
console.log($(this).val());
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email licls'+to_id+'"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" id= input_'+to_id+' />').on('keyup', function(e) { // input
console.log($(this).attr('id'));
$(this).removeClass('multiple_emails-error');
$('#'+orig_id).parent().find("label").remove();
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
$('#'+orig_id).parent().find("label").remove();
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container contnr_'+to_id+'" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
console.log(t.attr('id'));
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
var res_arr=JSON.parse($orig.val().toLowerCase().split(','))
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && res_arr.indexOf(arr[i].toLowerCase()) != -1) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if ( pattern.test(arr[i]) == true && res_arr.indexOf(arr[i].toLowerCase()) == -1) {
if($('#ulcls'+t.attr('id')).length < 4) {
$list.append($('<li class="multiple_emails-email licls'+to_id+'"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0) {
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
t.after('<label for='+orig_id+' style="color:#cc5965;">'+settings.invalid+'</label>');
}else {
$('#'+orig_id).parent().find("label").remove();
t.val("");
}
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
if($('.licls'+to_id).length > 4){
$('#input_'+to_id).css('display','none');
}else {
$('#input_'+to_id).css('display','block');
}
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
$(document).ready(function(){
$('#input_'+to_id).on("cut copy paste",function(e) {
e.preventDefault();
});
});
return $(this).hide();
});
};
})(jQuery);
But when i compile it with ng build --prod it's gives TypeError: $(...).multiple_emails is not a function , if it's not working correctly any other tool to convert from JavaScript to typescript ?
i had convert js into typesript using online compiler but nothing happened.
solved!!!!
finally i figure out the problem. it is in angular-cli.json.when i place my multiple_email.js after jquery-3.1.1.min.js,jquery.validate.min.js then it works like charm...!!! #rajesh thanks
I've been learning javascript and jquery and I've encountered a problem when I'm trying to validate my form fields using a jquery function. The problem is its working fine the first two times it is called (when I press the update button for a specific element )and whenever I'm trying to call it a third time (by pressing the update button for the same element as earlier ) it is calling itself but I clearly did not mention any recursive calls and am not calling it within the function again. I'm not sure why it is calling itself. Kindly help me out. I will be attaching the fiddle. After triggering reset in main.updateData(Object.assign({}, main.newObject), keys); in the third time its showing the name empty error which shouldn't be happening.
I've tried giving breakpoints and inspecting the reason behind this weird behaviour but I couldn't
The name field should show an error only when it is empty but third time it is showing error even when it is not empty
FIDDLE
validateFormData: function(value, keys, idCount) {
var keyIndex = 0;
main.newObject[keys[keyIndex++]] = idCount;
if (value == "update") {
main.newObject[keys[0]] = $(".active-contact").attr('id');
//alert("new updated id is " + main.newObject[keys[0]]);
}
var validElementsCount = 0;
var alphabet_pattern = /^[a-z]+\s*/i;
var email_pattern = /[a-z]{0,}[0-9]{0,4}[.]{0,1}[0-9]{0,4}[a-z]{0,8}[0-9]{0,4}[#][a-z]{0,20}[.](com)/i;
var number_pattern = /^[0-9]{10}$/;
var website_pattern = /^(www)[.][a-z]{1,20}[.](com)$/i;
/*Validating the form inputs against the regex pattern*/
if ($("#employee-name").val() == "") {
$("#employee-name-error").text("name cannot be empty");
} else if (!alphabet_pattern.test($("#employee-name").val())) {
$("#employee-name-error").text("Only alphabets are allowed");
} else {
validElementsCount++;
$("#employee-name-error").text("");
main.newObject[keys[keyIndex++]] = $("#employee-name").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex-1]]) + " key is " + keys[keyIndex-1]);
}
//employee email validation
if (email_pattern.test($("#employee-email").val()) || $("#employee-email").val() == "") {
$("#employee-email-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-email").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-email-error").text("Follow email pattern");
}
//employee mobile validation
if (number_pattern.test($("#employee-mobile").val()) || $("#employee-mobile").val() == "") {
$("#employee-mobile-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-mobile").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-mobile-error").text("Only 10 digit number is allowed");
}
//employee landline no validataion
if (number_pattern.test($("#employee-land-line").val()) || $("#employee-land-line").val() == "") {
$("#employee-land-line-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-land-line").val();
//alert("object is " + JSON.stringify(main.newObject[keys[keyIndex - 1]]) + " key is " + keys[keyIndex - 1]);
} else {
$("#employee-land-line-error").text("Only 10 digit number is allowed");
}
//employee website validation
if (website_pattern.test($("#employee-website").val()) || $("#employee-website").val() == "") {
$("#employee-website-error").text("");
validElementsCount++;
main.newObject[keys[keyIndex++]] = $("#employee-website").val();
} else {
$("#employee-website-error").text("Follow website pattern");
}
main.newObject[keys[keyIndex++]] = $("#employee-address").val();
if (validElementsCount == 5) {
if (value == "add") {
main.addEmployeeClick(Object.assign({}, main.newObject));
$(".employee-details-form").trigger("reset");
} else if (value == "update") {
//alert("new object is " + JSON.stringify(Object.assign({}, main.newObject), keys));
main.updateData(Object.assign({}, main.newObject), keys);
$(".employee-details-form").trigger("reset");
}
}
},
You can add .off() before #update-employee-btn click event binding in line 34.
$("#update-employee-btn").off().click(....)
Let me know if it works for you as well.
I am trying to get 4 values from the session,while i get two of them,other two are missing.i am still learning so please bear with me if my question is too naive.I have this checkbox and two radio buttons in a tree view.
ASP.NET Code
<div class="control-label col-sm-1">
<asp:TreeView runat="server" ID="tvAi" Font-Bold="true" ShowLines="true" EnableClientScript="true"
ShowExpandCollapse="true" ShowCheckBoxes="All" >
</asp:TreeView>
<asp:HiddenField ID="hdMobile" runat="server" />
</div>
Now when i go to the chrome developer tool and check the values of the radio button the session values are binding well and shows like this.
<input type="radio" checked="checked" id="rad_01-02-00000622" name="rdoC1" value="01-02-00000622_Deposit_1_109861">
Those four values separated by '_' are accountNumber_accountType_officeId_customerId respectively.
The Javascript Code which sets session
$(function() {
$("[id*=tvAi] input[type=checkbox]").bind("click",
function() {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
if (isChecked) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
}
$("input[type=radio]", childDiv).each(function() {
if (isChecked) {
$(this).attr("checked", "checked");
return false;
} else {
$(this).removeAttr("checked");
}
});
}
});
$("[id*=tvAi] input[type=radio]").bind("click",
function() {
//hdMobile
var parentDIV = $(this).closest("DIV");
if ($(this).is(":checked")) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
this.checked = false;
$('#CellNumberTextBox').focus();
return false;
}
$("input[type=checkbox]", parentDIV.prev()).attr("checked", "checked");
} else {
$("input[type=checkbox]", parentDIV.prev()).removeAttr("checked");
}
});
$("#SaveButton").bind("click",
function(e) {
$("#hdMobile").val("");
var tv = document.getElementById("<%= tvAi.ClientID %>");
var chkArray = tv.getElementsByTagName("input");
for (i = 0; i <= chkArray.length - 1; i++) {
if (i == 0) {
$.ajax({
type: "POST",
url: "AddNewCustomer.aspx/SetSession",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
}
});
}
if (chkArray[i].type == 'radio') {
if (chkArray[i].checked == true) {
if ($('#CellNumberTextBox').val() == null || $('#CellNumberTextBox').val() === '') {
bootbox.alert(
"Please enter the Cell Number because you have asked for the MobileBankingService.");
$('#CellNumberTextBox').focus();
$.hideprogress();
return false;
if ($("#hdMobile").val() == "" || $("#hdMobile").val() == null) {
$("#hdMobile").val(chkArray[i].value);
} else {
$("#hdMobile").val($("#hdMobile").val() + "," + chkArray[i].value);
}
}
}
}
});
});
My Code behind setting the session
[WebMethod]
public static void SetSession()
{
System.Web.HttpContext.Current.Session["AccountMoney"] = "";
}
And binding treeview code
private void BindTreeViewForMobile()
{
_customerId = Convert.ToInt64(Session["CustomerId"]);
if (_customerId > 0)
{
DataTable dtAccount = new DataTable();
dtAccount = BusinessLayer.SMS.SmsSetup.GetActiveAccountListByCustomer(_customerId);
tvAi.Nodes.Clear();
int redindex = 1;
string accNumber = "";
var customerMobileBanking = BusinessLayer.SMS.MobileBankingSetup.GetMobileBankingCustomer(_customerId);
foreach (DataRow dr in dtAccount.Rows)
{
if (customerMobileBanking != null)
{
foreach (Common.SMS.MobileBankingSetup ss in customerMobileBanking)
{
if (ss.AccountNumber == dr["account_number"].ToString())
{
if (ss.FeeCharges)
{
accNumber = ss.AccountNumber;
break;
}
else
{
accNumber = "";
break;
}
}
}
}
TreeNode master = new TreeNode(dr["account_number"].ToString(), dr["account_number"].ToString());
master.ShowCheckBox = true;
tvAi.Nodes.Add(master);
master.SelectAction = TreeNodeSelectAction.None;
string sk = "";
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
master.Checked = true;
}
}
for (int i = 0; i <= 1; i++)
{
TreeNode child = new TreeNode(sk, sk);
child.SelectAction = TreeNodeSelectAction.None;
child.ShowCheckBox = false;
if (accNumber != "")
{
if (accNumber == dr["account_number"].ToString())
{
child.Text = "<input type='radio' checked='checked' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
}
else
{
child.Text = "<input type='radio' id='rad_" + dr["account_number"].ToString() + "' name='rdoC" + redindex.ToString() + "' value ='" + sk + dr["account_number"].ToString() + "_" + dr["account"].ToString() + "_" + dr["office_id"].ToString() + "_" + _customerId.ToString() + "' />" + child.Text;
}
master.ChildNodes.Add(child);
}
redindex++;
}
}
}
The problem happens here when i am trying to get the session value in here
var sess = System.Web.HttpContext.Current.Session["AccountMoney"].ToString();
Here i only get the two session value not all 4.What am i doing wrong?Code must be too long for your time.any help appreciated.Thanks
I faced this before and search got me nowhere, went ahead and used cookies for the values I wanna read from JS. it works like a charm! Try it Get Cookies by name JS
This question already has answers here:
jQuery - how to check if an element exists?
(7 answers)
Closed 6 years ago.
how to check if jQuery .each() function cant find something, then change txt value to 'default'.
$(this).closest('.filter-select__dropdown-inner').find('> .button--checkbox.button--active').each(function(i) {
var val = $(this).val();
if (i == 0) {
txt = val;
} else {
txt = txt + ', ' + val;
}
});
im already try
if (i == null) {
txt = 'default';
}
but it doesnt work
Use .length in jquery to get the length
var lnt = $(this).closest('.filter-select__dropdown-inner').find('> .button--checkbox.button--active');
if(lnt.length > 0) {
lnt.each(function(i) {
var val = $(this).val();
if (i == 0) {
txt = val;
} else {
txt = txt + ', ' + val;
}
});
}
make use of .length and check its empty or not.
var objcollection = $(this).closest('.filter-select__dropdown-inner').
find('> .button--checkbox.button--active');
if(objcollection.length==0)
{
}
else
{
}
I want to write a multi column filter for one of my tables. I dont want for now to do it with plugins. I found that and its working but only for 1 column. Do you have any ideas how to modify it for all columns ?
$(".filter").keyup(function(e) { // filter is class
if (e.keyCode == 13) {
var indexColumn = $(this).attr('data-id');
console.log('INDEX ' + indexColumn);
console.log("value=%o", this.value);
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr")
//hide all the rows
if (this.value == "") {
jo.show();
return;
}
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
// console.log(data[d]);
return true;
}
}
return false;
}).show(); //show the rows that match.
updateTotals();
}
});
Fiddle demo
You can use each() jquery method in this case.
$(".filter").each(function() {
$(this).keyup(function(e) {
if (e.keyCode == 13) {
var indexColumn = $(this).attr('data-id');
console.log('INDEX ' + indexColumn);
console.log("value=%o", this.value);
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr")
//hide all the rows
if (this.value == "") {
jo.show();
return;
}
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function(i, v) {
var $t = $(this).children(":eq(" + indexColumn + ")");
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
// console.log(data[d]);
return true;
}
}
return false;
}).show(); //show the rows that match.
}
})
});
JS Demo