Creating Bootstrap Slider Inside JS For Loop - javascript

I have a JS feature in my app that allows the user to create a list one item at a time. I am trying now to give each item a bootstrap slider, but am encountering difficulties. I'm new to JS, so there might be some bad ideas in here (ones I would love help correcting). As it stands currently, if I take everything outside the <p> tags inside the for loop's added html out it works as intended, but with everything in it it renders a console error stating Uncaught TypeError: Cannot read property 'getAttribute' of null.
var proArray = [];
function addPro() {
proArray.push(document.getElementById("proInput").value);
document.getElementById("proForm").reset();
console.log(proArray);
for (var i = 0; i < proArray.length; i++) {
newItem = "<li><p>" + proArray[i] + "</p><input class='bootstrap-slider' type='text' id='proInput" + i + "' data-slider-id='proInput" + i + "' data-slider-min='0' data-slider-max='10' data-slider-value='5' /></li>";
}
var slider = new Slider('#proInput0', {
formatter: function(value) {
return 'Current value: ' + value;
}
});
document.getElementById("proList").innerHTML += newItem;
}
$('#proInput0').slider({
formatter: function(value) {
return 'Current value: ' + value;
}
});
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit" />
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
Can anyone help figure out where I'm going wrong and/or how to do this better?

The main issue is related on how you create on the fly the new elements:
In the for loop you create a variable, after create the slider but only after you append to the dom the new elements.
You never test if an element with the same id already exists.
Mainly, you never save the slider objects for future usage.
Every time you create a new slider you need to destroy and recreate it after a few milliseconds in order to make it works.
The snippet:
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>

Related

Searching name using JS and AJAX

I am making name searching bar with JS and AJAX.
If write name on searching bar, only searched member must be shown.
And these are my code.
html:
...
<input type="text" id="searchName" name="searchName" placeholder="Search name..." onkeyup="nameFilter()" >
</div>
<ul class="invite-list03"></ul>
<ul id="memberList" class="member-list-group"></ul>
AJAX:
for (let i in user.family) {
let familyUserSn = user.family[i].familyUserSn;
let familyMemberNm = user.family[i].familyMemberNm;
let userProflPhotoCn = user.family[i].userProflPhotoCn;
let memberCreatDt = user.family[i].memberCreatDt;
let today = common_getTodayWithHyphen();
let family;
let hideDeleteBtn = '<div class="button-area"><button type="button" class="button-member-hide">hide</button><button type="button" class="button-member-delete" id="memberDeletePopUp">delete</button></div>';
// If today is invited day, show New icon up side of family member image
if(memberCreatDt == today) {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure><label class="new">N</label></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
} else {
if(!userProflPhotoCn && userProflPhotoCn < 1) {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + DATA_NO_PROFILE + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
} else {
family = '<li class="family" id="'+ familyUserSn+'"><div class="member-profile"><figure class="default-bg"><img src="data:image/jpeg;base64,' + userProflPhotoCn + '" alt="profilePicture"></figure></div><p class="member-name">'+familyMemberNm+'</p>'+ hideDeleteBtn + '</li>';
}
}
// append to memberList
$("#memberList").append(family);
}
// I am first member of list
$(".family").first().click();
JS:
function nameFilter() {
let searchNameSave = $('#searchName').val();
if(searchNameSave.length > 0) {
$("#memberList").html("");
$("ul#memberList > li > .member-name:contains('" + searchNameSave + "')").parent().show();
}
}
What should I write in javascript? Now it doesn't working.
Thank you for your help.
Hi there are a few things you need to do
Ajax get source information
Filter the source data according to the search criteria
Remove the old data and replace the filtered data
You can set your code according to this idea
The following is an example of using jquery-ui + ajax + autocomplete for your reference
$("#queryname").autocomplete({
source: function(request, response) {
$.ajax({
type: 'get',
url: "https://raw.githubusercontent.com/DataTables/DataTables/master/examples/ajax/data/objects_salary.txt",
dataType: 'json',
success: function(data) {
const matcher = new RegExp(request.term, "i");
const datas = data['data'];
response($.map(datas, function(item) {
if (matcher.test(item.name)) {
return {
label: item.name,
value: item.name
}
}
}));
}
});
}
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input type='text' id='queryname' name='queryname' placeholder='Enter some text' />

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Getting 0x800a138f - JavaScript runtime error: Unable to get property 'client' of undefined or null reference

I'm making a chat application using SignalR API. I'm getting error as:
0x800a138f - JavaScript runtime error: Unable to get property 'client'
of undefined or null reference
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="/Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
SignalR Chat Room
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
You are referring to the client object of an undefined object. So I have been searching inside your code for
.client
These were the results:
chatHub.client.onConnected
chatHub.client.onNewUserConnected
chatHub.client.onUserDisconnected
chatHub.client.messageReceived
chatHub.client.sendPrivateMessage
So, if you look at the results, it becomes obvious that chatHub is undefined somewhere. This is how you initialize it:
var chatHub = $.connection.chatHub;
I wonder what is inside $.connection. Are you missing a script from your html?
A couple of things...
You're using an old signalr version, have you tried upgrading to the latest?
Otherwise; I had a similar problem, I had to solve it by setting up the connection without the generated proxy (/signalr/hubs).
See this link http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client and instead of setting it as a "generated proxy", implement it without it. (Search for "Without the generated proxy")

Build a array of div's id using each DIV inside section

I'm trying to get the ID of each DIV inside this HTML code
<section id="choices">
<div id="talla_choice_24" style="">
...
</div>
<div id="color_choice_25" style="">
...
</div>
<div id="sport_choice_26" style="">
...
</div>
<button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>
<section id="variations_holder" style="display: none"></section>
</section>
So I made this:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($(this).val());
})
return inputValues;
}
And I call here:
$('#choices').on("click", "#create-variation", function(e) {
var parent_id = $(this).closest("section").attr("id");
var element = getDivId(parent_id);
iterateChoices("", element[0], element.slice(1), 0);
});
I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));
But I get this error:
Uncaught TypeError: Object has no method 'each'
What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
if ($.isArray(choices) && choices.length > 0) {
element.each(function(index, item) {
if (counter == 0)
row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';
iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
});
} else {
html_temp = "";
$.each(element, function(index, item) {
html_temp += row + '<input value="' + item.value + '"><br>';
});
html += html_temp;
}
}
I also made some changes at this code:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push("#" + $(this).attr('id') + ' input:text');
});
return inputValues;
}
And now the error change to this:
Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'
UPDATE 2
I still continue change getDivId() function to build a array like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));
But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
});
return inputValues;
}
I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")
I think there is the problem
You are using the val method on a div element, which just returns an empty string. There is no each method on a string.
You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");
If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();
var arr = [];
$("#create-variation").on('click', function(){
$("#choices > div").each(function(a,b){
arr.push($(this).text());
});
});
After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
var inputValues = [];
$("#" + div + ' > div').each(function() {
inputValues.push($("#" + $(this).attr('id') + " input:text"));
});
return inputValues;
}

View page does not recognize null element in load

I have an javascript function that generates links in my page based on a DropDown. I'm checking the javascript function in two places; when the DropDown changes with attribute "onchange", and when the page is loaded. The error is generated when the page is loaded without element on viewbag, my javascript is not recognizing the null element for generate links without the information on viewbag.
<p>Pesquisar por: #Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" })
<div id="dadosFornecedor">
#if (ViewBag.CurrentFornecedor != null)
{
<fieldset>
<legend>#ViewBag.CurrentFornecedor.RazaoSocial</legend>
<b>Razão Social:</b> #ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> #ViewBag.CurrentFornecedor.Endereco
#Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor })
<input type="button" class="btn" onclick="removerFornecedor();" value="Remover Fornecedor" />
<br />
<br />
</fieldset>
<br />
}
</div>
<script type="text/javascript">
$(function () {
alteraFiltro();
});
function removerFornecedor() {
var div = $("#dadosFornecedor");
var hidden = $("#idFornecedor");
div.empty();
div.append("<input type='hidden' name='deletarFornecedor' value='true' />")
}
function alteraFiltro() {
var urlCodigo = $("#linkCodigo");
var urlLancamento = $("#linkLancamento");
var urlPagamento = $("#linkPagamento");
var urlFornecedor = $("#linkFornecedor")
var dropValue = $("#tipoPesquisa").val();
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
} else{
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
}
}
</script>
If the issue is caused by ViewBag.CurrentFornecedor not having a value when the view is first loaded, try altering your javascript along these lines:
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
// ...
}
else {
urlCodigo.attr("href", "saidasDiversassortOrder=#ViewBag.CodigoSortParm&idFornecedor="
+ #{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1}
+ "&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
// ...
}

Categories

Resources