I currently am working on a feature for a web app that allows users to dynamically search and filter a list of cards. I've accomplished the filtering and search, but as the search results grow, I end up with either an incredibly slow page, or a very large number of results to sift through. I thought pagination might be a solution given the maximum number of results are in the thousands, and eventually I'd like to have very broad filter buttons, as well as text-based search.
A screenshot of it in action:
The code is as follows:
deckbuilder.js
document.addEventListener("turbolinks:load", function() {
$(document).on("click", ".deck-adjust-button", adjustDeck)
$(document).on("click", "#decklist-submit", submitDecklist)
$(document).on("input", "#list-search", updateMiniList)
})
function adjustDeck(e) {
card_name = $(this).parents('tr').data("name")
card_name_sanitized = card_name.replace(/\s+/g, '-').replace(/,/g, '').replace(/'/g, '').toLowerCase();
num_cards = $(this).parents('tr').find("#num-cards").val()
deck = $(this).text().toLowerCase() + "-deck"
console.log(card_name + "|" + num_cards + "|" + deck)
deck_div = $("#" + deck)
deck_div.find("#" + card_name_sanitized).remove()
if (parseInt(num_cards) > 0) {
deck_div.append("<div id=" + card_name_sanitized + ">" + num_cards + "x " + card_name + "</div>")
}
}
function submitDecklist(e) {
e.preventDefault()
deck_divs = $(".deck")
decklist_decks = []
decklist_name = $('#name').val()
decklist_description = $("#description").val()
deck_divs.each(function(div) {
deck = $(deck_divs[div])
deck_name_raw = deck.find('div').attr("id")
deck_name = deck_name_raw.split("-")[0]
deck_name = deck_name.charAt(0).toUpperCase() + deck_name.slice(1)
deck_div = deck.find('#' + deck_name_raw)
cards_array = []
deck_div.children().each(function() {
card_text = $(this).text().trim()
card_name = card_text.substr(card_text.indexOf(' ')+1)
card_num = parseInt(card_text.substr(0,card_text.indexOf(' ')).replace(/x/g, ''))
cards_array.push({
name: card_name,
num: card_num,
})
})
decklist_decks.push({
name: deck_name,
cards: cards_array
})
})
decklist = {
decklist: {
name: decklist_name,
description: decklist_description,
decks: decklist_decks
}
}
$.ajax({
method: "POST",
url: "/decklists",
data: decklist
})
.done(function( msg ) {
window.location.replace("/decklists/" + msg.id);
})
.fail(function( msg) {
window.location.replace("/decklists/new");
})
}
function updateMiniList(e) {
inputValue = $(this).val().toLowerCase()
listEntries = $(this).parents().siblings('#mini-card-list').find('tr')
listEntries.each(function() {
entry = $(this)
entryName = $(this).data("name").toLowerCase()
if (!entryName.includes(inputValue)) {
entry.hide()
} else {
entry.show()
}
})
if(inputValue.length > 2) {
data = { "name": inputValue }
ApiCall("POST", "/cards/search", data, appendCards)
}
}
function ApiCall(method, target, data, callback) {
$.ajax({
method: method,
url: target,
data: data,
success: callback
})
}
function appendCards(cards) {
cards.forEach(function(card) {
name = card.name
newCardDiv = $('<tr data-name="' + name + '">\
<td>\
<select class="form-control" id="num-cards">\
<option value=0>0</option>\
<option value=1>1</option>\
<option value=2>2</option>\
<option value=3>3</option>\
<option value=4>4</option>\
</select>\
</td>\n\
<td>' + name + '</td>\n\
<td>\
<div class="btn-group btn-group-sm" role="group">\
<button type="button" class="btn btn-secondary deck-adjust-button">Main</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Stone</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Side</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Ruler</button>\
</div>\
</td>\
</tr>')
$('#mini-card-list').find('table').append(newCardDiv)
});
}
new.html.erb (Page interacting with JS)
<div class="container">
<div class="row">
<div class="col">
<h2>Create a New Decklist</h2>
</div>
</div>
<div class="row">
<div class="col-md-5">
<hr>
<h4>Decks</h4>
<hr>
<%= render "decklists/deck_div", deck_name: "Ruler" %>
<%= render "decklists/deck_div", deck_name: "Main" %>
<%= render "decklists/deck_div", deck_name: "Stone" %>
<%= render "decklists/deck_div", deck_name: "Side" %>
<%= render "decklists/form", decklist: #decklist %>
</div>
<div class="col-md-7">
<%= render "cards/mini_list", cards: #cards %>
</div>
</div>
</div>
deck_div partial
<div class="row">
<div class="col deck">
<hr>
<h4><%= deck_name %></h4>
<hr>
<div id="<%= deck_name.downcase + "-deck" %>">
</div>
</div>
</div>
Mini-List Partial
<div class="col">
<hr>
<h4>Cards</h4>
<hr>
<div>
<input type="text" placeholder="Search" class="form-control" id="list-search">
</div>
<div id="mini-card-list" style="overflow:scroll; height:400px;">
<table class="table">
</table>
</div>
</div>
Related
i want to press the edit button to change it to a save button and the delete button has te become cancel. when you press the button the text has to become a textarea so you can change it in the database.
this is the front end. know it only change the text of the button
<% itemsSmall.forEach(function(itemsSmall, index) {%>
<%if( String(image._id) === String(itemsSmall.imageId)){
%>
<div class="position-relative">
<div>
<p class="d-inline-block"><strong><%= itemsSmall.title %>:</strong> <%=itemsSmall.smallInformation %> </p>
</div>
<div style="display: none;" id="Test<%=String(itemsSmall.imageId)%>">
change text
</div>
<% if(image.userId == user.userId || user.admin > 2){ %>
<div class="col-12 col-md-6">
<button onclick="quoteAdd('{!!$product->id!!}', this)" id="inquireButton" class="btn btn-sm btn-warning float-right me-md-2">edit</button>
</div>
<div class="col-12 col-md-6">
<form action="/view/deleteSmall/<%= itemsSmall._id %>?_method=delete" method="POST">
<textarea name="imageId" id="imageId" hidden><%= image._id %></textarea>
<button class="btn btn-sm btn-danger float-right me-md-2" type="submit">delete</button>
</form>
<%}%>
</div>
</div>
<%}%>
<% }) %>
</div>
here is the peace of javascript for the button
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#myselection').on('change', function(){
var demovalue = $(this).val();
$("div.myDiv").hide();
$("#show"+demovalue).show();
});
});
function quoteAdd(productId, button) {
$(button).text('save');
}
</script>
and then a last we have the backend
//create the small information blocks
router.post("/uploadSmall", (req, res) => {
const id = req.params.id; //set the id from the page
//create the image
itemsSmall
.findById(id)
.then((result) => {
//set the image in een obj
var obj = {
title: req.body.Title,
smallInformation: req.body.smallInformation,
userId: req.auth.userId,
imageId: req.body.imageId,
};
//all the thing of the obj set to the model
itemsSmall.create(obj, (err, items) => {
if (err) {
console.log(err);
} else {
items.save(); //upload the model
res.redirect("/view/" + req.body.imageId);
}
});
})
.catch((err) => {
console.log(err);
});
});
router.post("/deleteSmall/:id", (req, res) => {
const id = req.params.id; //get the id of the text
//find the model in the database and delete it
itemsSmall.findByIdAndRemove(id, (err) => {
if (err) {
console.log(err);
return res.json({ success: false });
}
res.redirect("/view/" + req.body.imageId);
});
});
i found the anwser
you have to pass a value with the button and then change it.
here is the code
this is the html
<% itemsSmall.forEach(function(itemsSmall, index) {%>
<%if( String(image._id) === String(itemsSmall.imageId)){
%>
<div class="position-relative">
<div>
<p class="d-inline-block"><strong><%= itemsSmall.title %>:</strong> <%=itemsSmall.smallInformation %> </p>
</div>
<div style="display: none;" id="<%=itemsSmall._id%>">
your daddy
</div>
<% if(image.userId == user.userId || user.admin > 2){ %>
<div class="col-12 col-md-6">
<button onclick="quoteAdd('<%= itemsSmall._id %>', '{!!$product->id!!}', this)" value="<%= itemsSmall._id %>" id="inquireButton" class="btn btn-sm btn-warning float-right me-md-2">edit</button>
</div>
<div class="col-12 col-md-6">
<form action="/view/deleteSmall/<%= itemsSmall._id %>?_method=delete" method="POST">
<textarea name="imageId" id="imageId" hidden><%= image._id %></textarea>
<button class="btn btn-sm btn-danger float-right me-md-2" type="submit">delete</button>
</form>
<%}%>
</div>
</div>
<%}%>
<% }) %>
here is the javascript part
function quoteAdd(val, productId, button) {
var x = document.getElementById(val)
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
$(button).text(val);
}
i dont think it is the best way but it works
I have a page with one with one link "COUNTRY", by hitting this link, under it appear some other links, which are group of countries. There is also one of the links called "Individual", by hitting that link appears one autocomplete field, where the user can start typing and choose one country.
I want by choosing the country to change some of the hidden fields values and than to submit the form.
The form submission works, but unfortunately there are no POST fields sent.
Here is the HTML & JS code:
<form method="POST" action="" accept-charset="UTF-8" id="news_search_form">
<input name="_token" type="hidden" value="tAB6ZU6sNafRUNBLiPyhiuCbEDQVGD4waxNbT3Yk">
<div class="row threelinks">
<div class="col-xs-12 col-sm-12 col-md-3">
<a href="javascript:;" class="btn_filter_category" data-href="country">
<div class="links_new link_hover">COUNTRY</div>
</a>
<input type="hidden" id="select_country" name="select_country" value="214">
<input type="hidden" id="filter_country" name="filter_country" value="0">
</div>
</div>
<div class="row " style="margin-top: 5px; display: none;" id="country_filters">
<div class="col-md-12">
<div class="owl-carousel col-md-12">
<div class="item">
<div class="top_sub_link">
Top 4
</div>
</div>
<div class="item">
<div class="top_sub_link">
EU
</div>
</div>
<div class="item">
<div class="top_sub_link">
Top 8
</div>
</div>
<div class="item">
<div class="top_sub_link">
Non EU
</div>
</div>
<div class="item">
<div class="top_sub_link">
Individual <i class="fa fa-pencil"></i>
<input type="text" class="form-control input-lg" id="individual_country" name="individual_country" style="font-size: 11px; text-align: center; display: none;"/>
<div id="no-result" style="display: none;">No results found</div>
</div>
</div>
<div class="item">
<div class="top_sub_link">
Reset
</div>
</div>
<div class="owl-nav"></div>
</div>
</div>
</div>
</form>
<script>
var filters = ['country'];
$(document).ready(function() {
$('a.btn_filter_category').on('click', function() {
var filter = $(this).attr('data-href');
show_filter(filter + '_filters');
unselect_filters();
$(this).find('.links_new.link_hover').removeClass('link_hover').addClass('link_hover_selected');
});
$(".filter_link").on('click', function() {
var filter = $(this).attr('data-href');
var value = $(this).attr('data-value');
$('#filter_' + filter).val(value);
$('#select_' + filter).val(0);
$("#news_search_form").submit();
});
$(".individual_link").on('click', function() {
var filter = $(this).attr('data-href');
$(this).remove();
$('#individual_' + filter).show();
});
});
$(function () {
var filter = 'country';
var url = "{{ url('country/search/'.$lang) }}";
$("#individual_" + filter).autocomplete({
source: function(request, response) {
$.ajax({
url: url,
dataType: "json",
type: "GET",
data: {
name: request.term
},
success: function(data){
response( $.map( data, function( item ) {
// alert(item.label);
return {
label: item.name,
value: item.value // EDIT
}
}));
}
})
},
select: function(event, ui) {
$('#filter_' + filter).val(0);
$('#select_' + filter).val(ui.item.value);
$("#news_search_form").submit();
}
});
});
function unselect_filters() {
$('div.links_new').each(function(i, obj) {
$(this).removeClass('link_hover').removeClass('link_hover_selected').addClass('link_hover');
});
}
function show_filter(selected_class) {
var arrayLength = filters.length;
for (var i = 0; i < arrayLength; i++) {
var class_name = filters[i] + '_filters';
if(selected_class != class_name) $('#'+ class_name).hide();
else $('#'+ class_name).show();
}
}
function reset_filter(filter) {
$('#filter_' + filter).val(0);
$('#select_' + filter).val(0);
$("#news_search_form").submit();
}
</script>
i found the solution.
The autocomplete submit form is working fine. Unfortunately there was some redirect after the submit, which was causing and empty POST array.
For some reason data validation doesn't work. Although, if I add an alert statement after valid() method inside .click(), it will alert, which means that data is considered valid anyways. I tried different approaches including making actionbutton outside form in html file, but that didn't solve the problem. What else could that be?
Currently there are no exceptions or errors.
JavaScript:
$(function () {
$("#EmployeeForm").validate({
rules: {
TextBoxTitle: { maxlength: 4, required: true, validTitle: true },
TextBoxFirstname: { maxlength: 25, required: true },
TextBoxLastname: { maxlength: 25, required: true },
TextBoxEmail: { maxlength: 40, required: true, email: true },
TextBoxPhone: { maxlength: 15, required: true }
},
errorElement: "div",
messages: {
TextBoxTitle: {
required: "required 1-4 chars.", maxlength: "required 1-4 chars.",
validTitle: "Mr. Ms. Mrs. or Dr."
},
TextBoxFirstname: {
required: "required 1-25 chars.", maxlength: "required 1-25 chars."
},
TextBoxLastname: {
required: "required 1-25 chars.", maxlength: "required 1-25 chars."
},
TextBoxPhone: {
required: "required 1-15 chars.", maxlength: "required 1-15 chars."
},
TextBoxEmail: {
required: "required 1-40 chars.", maxlength: "required 1-40 chars.",
email: "need vaild email format"
}
}
});
//custom validator
$.validator.addMethod("validTitle", function (value, element) { // custom rule
return this.optional(element) || (value == "Mr." || value == "Ms." || value == "Mrs." || value == "Dr.");
}, "");
//click event handler for the employee list
$("#employeeList").click(function (e) {
if (!e) e = window.event;
var Id = e.target.parentNode.id;
if (Id === 'employeeList' || Id === '')
Id = e.target.id;
var data = JSON.parse(localStorage.getItem('allemployees'));
clearModalFields();
//add, update or delete?
if (Id === '0') {
setupForAdd();
$('#ImageHolder').html('');
} else {
setupForUpdate(Id, data);
}
});
getAll('');
$("#srch").keyup(function () {
filterData();
});
function filterData() {
filteredData = [];
allData = JSON.parse(localStorage.getItem('allemployees'));
$.each(allData, function (n, i) {
if (~i.LastName.indexOf($("#srch").val())) {
filteredData.push(i);
}
});
buildEmployeeList(filteredData, false);
}
function loadDepartmentDDL(empdiv) {
html = '';
$('#ddlDivs').empty();
var alldepartments = JSON.parse(localStorage.getItem('alldepartments'));
$.each(alldepartments, function () {
html += '<option value="' + this['Id'] + '">' + this['DepartmentName'] + '</option>';
});
$('#ddlDivs').append(html);
$('#ddlDivs').val(empdiv);
}
$("#actionbutton").click(function () {
if ($("#EmployeeForm").valid()) {
if ($('#actionbutton').val() === 'Update') {
update();
} else {
add();
}
}
else {
$("#lblstatus").text("fix existing problems");
$("#lblstatus").css({ "color": "red" });
}
return false;
});
$('#deletebutton').click(function () {
var deleteEmployee = confirm('Really delete this employee?');
if (deleteEmployee) {
_delete();
return !deleteEmployee;
}
else {
return deleteEmployee;
}
});
function setupForUpdate(Id, data) {
$('#actionbutton').val('Update');
$('#modaltitle').html('<h4>Employee Update</h4>');
$('#deletebutton').show();
$.each(data, function (index, employee) {
if (employee.Id === parseInt(Id)) {
$('#TextBoxEmail').val(employee.Email);
$('#TextBoxTitle').val(employee.Title);
$('#TextBoxFirstname').val(employee.FirstName);
$('#TextBoxLastname').val(employee.LastName);
$('#TextBoxPhone').val(employee.Phoneno);
$('#ImageHolder').html('<img height="120" width="110" src="data:image/png;base64,' + localStorage.getItem('StaffPicture') + '"/>');
localStorage.setItem('Id', employee.Id);
localStorage.setItem('DepartmentId', employee.DepartmentId);
localStorage.setItem('Timer', employee.Timer);
loadDepartmentDDL(employee.DepartmentId);
return false;
} else {
$('#status').text('no employee found');
}
});
$('#theModal').modal('toggle');
}
function setupForAdd() {
clearModalFields();
$('#actionbutton').val('Add');
$('#modaltitle').html('<h4>Add New Employee</h4>');
$('#deletebutton').hide();
$('#theModal').modal('toggle');
}
//build the list
function buildEmployeeList(data, allemployees) {
$('#employeeList').empty();
div = $('<div class="list-group"><div>' +
'<span class="col-xs-4 h3">Title</span>' +
'<span class="col-xs-4 h3">First</span>' +
'<span class="col-xs-4 h3">Last</span>' +
'</div>');
div.appendTo($('#employeeList'))
if (allemployees) {
localStorage.setItem('allemployees', JSON.stringify(data));
}
btn = $('<button class="list-group-item" id="0">...Click to add employee</button>');
btn.appendTo(div);
$.each(data, function (index, emp) {
btn = $('<button class="list-group-item" id="' + emp.Id + '">');
btn.html(
'<span class="col-xs-4" id="employeetitle' + emp.Id + '">' + emp.Title + '</span>' +
'<span class="col-xs-4" id="employeefname' + emp.Id + '">' + emp.FirstName + '</span>' +
'<span class="col-xs-4" id="employeelastname' + emp.Id + '">' + emp.LastName + '</span>');
btn.appendTo(div);
});
}
//get all employees
function getAll(msg) {
$('#status').text('Finding employee information...');
ajaxCall('Get', 'api/employees', '')
.done(function (data) {
buildEmployeeList(data, true);
if (msg === '')
$('#status').text('Employees Loaded');
else
$('#status').text(msg + ' - Employees Loaded');
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
ajaxCall('Get', 'api/departments/', '')
.done(function (data) {
localStorage.setItem('alldepartments', JSON.stringify(data));
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert('error');
});
}
function clearModalFields() {
$('#TextBoxFirstname').val('');
$('#TextBoxLastname').val('');
$('#TextBoxEmail').val('');
$('#TextBoxTitle').val('');
$('#TextBoxPhone').val('');
$('#modalStatus').text('');
localStorage.removeItem('Id');
localStorage.removeItem('DepartmentId');
localStorage.removeItem('Timer');
loadDepartmentDDL(-1);
}
function add() {
emp = new Object();
emp.Title = $("#TextBoxTitle").val();
emp.FirstName = $("#TextBoxFirstname").val();
emp.Lastname = $("#TextBoxLastname").val();
emp.Phoneno = $("#TextBoxPhone").val();
emp.Email = $("#TextBoxEmail").val();
emp.DepartmentId = $("#ddlDivs").val();
ajaxCall('post', 'api/employees/', emp)
.done(function (data) {
getAll(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
return false;
}
function update() {
emp = new Object();
emp.Title = $("#TextBoxTitle").val();
emp.FirstName = $("#TextBoxFirstname").val();
emp.Lastname = $("#TextBoxLastname").val();
emp.Phoneno = $("#TextBoxPhone").val();
emp.Email = $("#TextBoxEmail").val();
emp.Id = localStorage.getItem('Id');
emp.DepartmentId = localStorage.getItem('DepartmentId');
emp.DepartmentName = $('#ddlDivs').val();
emp.Timer = localStorage.getItem('Timer');
if (localStorage.getItem('StaffPicture')) {
emp.Picture64 = localStorage.getItem('StaffPicture');
}
ajaxCall('put', 'api/employees/', emp)
.done(function (data) {
$("#status").text(data);
if (data.indexOf('not') == -1) {
$('#ImageHolder').html('<img height="120" width="110" src="data:image/png;base64,' + localStorage.getItem('StaffPicture') + '"/>')
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
return false;
}
$("input:file").change(() => {
var reader = new FileReader();
var file = $('#fileUpload')[0].files[0];
if (file) {
reader.readAsBinaryString(file);
}
reader.onload = function (readerEvt) {
//get binary data then convert to encoded string
var binaryString = reader.result;
var encodedString = btoa(binaryString);
localStorage.setItem('StaffPicture', encodedString);
}
});
//delete employee
function _delete() {
ajaxCall('Delete', 'api/employees/' + localStorage.getItem('Id'), '')
.done(function (data) {
getAll(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
}
//cal ASP.NET WEB API server
function ajaxCall(type, url, data) {
return $.ajax({
type: type,
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: true
});
}
function errorRoutine(jqXHR) {
if (jqXHR.responseJSON == null) {
$('#status').text(jqXHR.responseText);
}
else {
$('#status').text(jqXHR.responseJSON.Message);
}
if (jqXHR.responseJSON === null) {
$("#lblstatus").text(jqXHR.responseText);
}
else {
$("#lblstatus").text(jqXHR.responseJSON.Message);
}
} //errrorRoutine
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<link href="Content/employee.css" rel="stylesheet" />
<link rel="icon" href="data:;base64,iVBORw0KGgo=" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" style="background-color: #686868">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">#2</a>
<div class="col-xs-2"> </div>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav" id="menu">
<li>Home</li>
<li>CRUD</li>
</ul>
<div class="input-group col-xs-push-3 col-sm-2 col-xs-4 navbar navbar-brand" style="position:absolute; left:1200px;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
<input type="text" id="srch" class="form-control form-md">
</div>
<div id="version" style="color:white; float:right;"><p>v2.0</p></div>
</div>
</nav>
<div class="container">
<div style="padding-top:15%;">
<div class="panel panel-default">
<div class="panel-heading text-center" id="status" style="font-weight:bold;"></div>
<div class="panel-body">
<div id="employeeList"></div>
</div>
</div>
</div>
</div>
<form id="EmployeeForm" name="EmployeeModalForm" method="post" action="">
<div class="modal fade" id="theModal" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
<div id="modelTitle"></div>
<h4>Employee Update - v2.0</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
Employee Information
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-4">Title:</div>
<div class="col-xs-8"><input type="text" placeholder="enter title" id="TextBoxTitle" class="form-control" /></div>
</div>
<div class="row">
<div class="col-xs-4">First:</div>
<div class="col-xs-8"><input type="text" placeholder="enter first name" id="TextBoxFirstname" class="form-control" value="Joe" /></div>
</div>
<div class="row">
<div class="col-xs-4">Surname:</div>
<div class="col-xs-8"><input type="text" placeholder="enter last name" id="TextBoxLastname" class="form-control" value="Blow" /></div>
</div>
<div class="row">
<div class="col-xs-4">Phone#:</div>
<div class="col-xs-8"><input type="text" placeholder="enter phone" id="TextBoxPhone" class="form-control" value="(555)555-5555" /></div>
</div>
<div class="row">
<div class="col-xs-4">Email:</div>
<div class="col-xs-8"><input type="text" placeholder="enter email" id="TextBoxEmail" class="form-control" value="jb#ss.com" /></div>
</div>
<div class="row">
<div class="col-xs-4"><strong>Department:</strong></div>
<div class="col-xs-8">
<select id="ddlDivs" name="ddlDivs" class="form-control"></select>
</div>
</div>
<div class="row">
<div class="col-xs-4">Picture:</div>
<div class="col-xs-8" id="ImageHolder" style="padding-top:2%;" />
</div>
</div>
<div class="panel-footer"> </div>
</div>
</div>
<div class="modal-footer">
<div class="col-xs-8"><input id="fileUpload" type="file" /></div>
<div class="col-xs-4"><input type="submit" value="Update" id="actionbutton" class="btn btn-default" style="position:absolute; right:100px; z-index:100; top:30px" /></div>
<div class="col-xs-4"><input type="button" value="Delete" id="deletebutton" class="btn btn-danger" style="position:absolute; top:30px; right:5px;" /></div>
<label class="col-xs-12 text-center row" id="lblstatus" style="padding-top:10px;"></label>
<div id="status" class="text-left" style="padding-top:5%;"></div>
</div>
</div>
</div>
</div>
</form>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/jquery.validate.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/employeecrud.js?newversion"></script> <!--Google Chrome does not load the newest version of the code. Adding unique string helps-->
</body>
</html>
jQuery validator works off of the name of the element not its id.
So for lets say for example on your email input you should add: name="TextBoxEmail"
Like this:
<input type="text" placeholder="enter email" id="TextBoxEmail" name="TextBoxEmail"
class="form-control" value="jb#ss.com" />
I have some jQuery that when a value is entered will change from Price Range to whatever that value is. When that value is removed by the user, I need it to default back to Price Range. I have tried an else if statement, but my JS/jQuery is not good at all and that is not working. Not sure where to go from here.
jQuery:
function modPrice() {
if ($("#listing-price-selector") && $("#listing-price-selector").next()) {
var mn = $("#listing-price-selector").next().find("#listing_search_form_min_price").val();
var mx = $("#listing-price-selector").next().find("#listing_search_form_max_price").val();
if (mn || mx) {
mn = (mn == "") ? 0 : mn;
mx = (mx == "") ? 0 : mx;
$("#priceBox").val(mn + " to " + mx);
if (parseFloat($("#listing_search_form_max_price").val()) > 0) {
$("#listing-price-selector").text(" $" + mn + " to $" + mx);
} else {
$("#listing-price-selector").text(" $" + mn);
}
}
}
}
HTML:
<div class="col-md-2 col-xs-6">
<a tabindex="0" class="button btn-transparent" id="listing-price-selector" role="button" data-toggle="popover">Price Range <span class="caret"></span></a>
</div>
<div id="listing-price-content" style="display: none;">
<div class="container-fluid">
<div class="row">
<div class="col-xs-6">
<div class="input-group input-group-sm">
<span class="input-group-addon" id="basic-addon1">$</span>
<%= f.text_field :min_price, class: "form-control", placeholder: "Min Rent", data: { "binding-name" => "min-price" } %>
</div>
</div>
<div class="col-xs-6">
<div class="input-group input-group-sm">
<span class="input-group-addon" id="basic-addon1">$</span>
<%= f.text_field :max_price, class: "form-control", placeholder: "Max Rent", data: { "binding-name" => "max-price" } %>
</div>
</div>
</div>
</div>
</div>
What you probably need to change it dynamically is a listener. Here are steps on how to do it with some documentation.
Add change listener on the min/max input fields that will change the listing-price-selector on the page when the values are edited.https://api.jquery.com/change/
Add a html data-attribute to the listing-price-selector with the default price. When the values of the input fields are missing, show the default pricing by selecting the changing the text to the data value. https://api.jquery.com/data/
I saw a code that checks the radio button by value, but how do I do this by id? My current scenario is that I'm populating a table by appending html codes using ajax. I'm looping the prices of a certain item while building the html table. After that, I need to check the radio button of a price where default flag is equal to 'Y'.
Here's my if statement that checks the radiobutton by value only, this is not working yet as my radiobutton values are null, only the id and name has value:
if (item.defaultflag == 'Y')
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.channelid + '"]').prop('checked', true);
else
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.channelid + '"]').prop('checked', false);
Complete code:
$.ajax({
url: '/Item/RetrievePrice',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
cache: false,
async: true,
success: function (data) {
var trHTML = "";
debugger;
trHTML = '<tbody id="dbBody2">';
$.each(data, function (i, item) {
trHTML += '<tr><td class="hidden">' + item.itemid + '</td>' +
'<td style="width:20px"><label><input type="radio" name="rbDefaultPrice" id = "iPrice_' + item.itemid + '" /></label></td>' +
'<td>' + item.itemprice + '</td>' +
'<td>' + ToJavaScriptDate(item.startdate) + '</td>' +
'<td>' + ToJavaScriptDate(item.enddate) + '</td>' +
'</tr>';
//How do I check the radiobutton by id?
if (item.defaultflag == 'Y')
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.itemid + '"]').prop('checked', true);
else
$('#divItemPrice').find(':radio[name=rbDefaultPrice][value="iPrice_' + item.itemid + '"]').prop('checked', false);
});
trHTML += '</tbody>';
$("#tblItemPrice tbody").remove();
$('#tblItemPrice').append(trHTML);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error! " + xhr.status);
}
});
View (modal part)
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div id="divItemPrice" class="" style="border: 0px solid green; ">
<table id="tblItemPrice" onclick="gettabledata('tblItemPrice', '0,2,3,4', 'itemPriceId,itemPrice,strtDt,endDt')" class="table table-hover table-bordered table-striped bootgrid-table" aria-busy="false" padding-left:10px;">
<thead>
<tr class="inner-table-head">
<th class="hidden">
#Html.DisplayNameFor(model => model.itemPriceId)
</th>
<th>
Price
</th>
<th>
Start Date
</th>
<th>
End Date
</th>
</tr>
</thead>
<tbody id="bodyToAppend">
</tbody>
</table>
</div>
<div class="form-group">
<div class="row form-row">
<span class="form-item">
#Html.HiddenFor(m => m.itemPriceId)
#Html.LabelFor(m => m.itemPrice, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.itemPrice, new { #class = "form-control input-sm" })
</span>
</div>
<div class="row form-row">
<span class="form-item ">
#Html.LabelFor(m => m.strtDt, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.strtDt, new { #class = "form-control input-sm", #Value = "" })
</span>
</div>
<div class="row form-row">
<span class="form-item ">
#Html.LabelFor(m => m.endDt, new { #class = "lbl-width" })
#Html.TextBoxFor(m => m.endDt, new { #class = "form-control input-sm", #Value = "" })
</span>
</div>
<div class="row form-row maintenance-btn">
<div class="btn-group">
<input type="submit" id="btnSavePrice" value="Save" class="btn btn-theme btn-sm" formmethod="post" />
<input type="submit" id="btnUpdatePrice" value="Update" class="btn btn-theme btn-sm" formmethod="post" style="display:none" />
#*<input type="submit" id="btnCancelPrice" value="Cancel" class="btn btn-theme btn-sm" />*#
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="closeModal" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
The code in your if/else block cannot work because its attempting to .find() and element in the DOM which does not even exist yet (you have not added it). And even if you did add the <tr> to the DOM in each iteration it would result in poor performance (searching the whole table in each iteration).
A simple way to solve this (and much easier to debug the html your generating) is to create a hidden template that is cloned and added in each iteration. I also assume that you want to add the value of itemprice as the value attribute of the radio button so that you can get the value of the selected radio button using var price = $('input[name="rbDefaultPrice"]').val();
<table id="template" style="display:none;">
<tr>
<td>
<label>
<input type="radio" name="rbDefaultPrice" class="radio" />
<span class="price"></span>
</label>
</td>
<td class="startdate"></td>
<td class="enddate"></td>
</tr>
</table>
Then in the .each() loop, clone the template, update its values and append it to the DOM
var tbody = $('#tblItemPrice tbody');
....
success: function (data) {
tbody.empty() // remove existing rows
$.each(data, function (i, item) {
// clone the template row
var row = $('#template').clone().find('tr');
// update properties
var radio = row.find('.radio');
radio.val(item.itemprice);
if (item.defaultflag == 'Y') {
radio.prop('checked', true);
}
row.find('.price').text(item.itemprice);
row.find('.startdate').text(....
// add the row to the DOM
tbody.append(row);
});
}
Side note: Its not clear what your ToJavaScriptDate() function is doing, but I suggest you just pass the correctly formatted value to client so you can just use row.find('.startdate').text(item.startdate); etc