I would like to remove my list result when I search second element from search box.
I have tried some jquery code but I assume its not working because I am using it on wrong place or wrong content.
Any suggestion will be highly appreciated.
Here is the my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Kunde</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script src="autocomplete/jquery.easy-autocomplete.min.js"></script>
<link href="autocomplete/easy-autocomplete.min.css" rel="stylesheet" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="custom.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="jumbotron">
<div class="col-lg-4">
<input type="text" id="KUNDE" size="50" placeholder="Search by name." />
</div>
<div class="col-lg-2">
<input class="btn btn-default" id="buton" type="submit" value="search" onclick="find();" />
</div>
</div>
<ul id="list"></ul>
<div class="footer"><p> © Copyright 2016</p> <strong>RackPeople</strong>.</div>
</div>
<script>
$(function () {
$("#KUNDE").focus();
});
$(document).keypress(function (e) {
if (e.which == 13) {
$("#buton").click();
}
});
//$('#button').on('click', function () {
// $(root).empty();
//});
//$("li:eq(3)", $(root)).remove();
//$('ul').eq(1).toggleClass('hidden');
//$('#ul').empty();
//$("#buton").click(function () {
// $("#list").remove();
//});
//$('#buton').on('click', '.itemDelete', function () {
// $(this).closest('li').remove();
//});
var uri = 'json.json';
function find() {
var info = $('#KUNDE').val();
$.getJSON(uri)
.done(function (data) {
var item = data.filter(function (obj) {
return obj.name === info || obj.ID === info;
})[0];
if (typeof item !== 'undefined' || item !== null) {
$("ul").append("<li>" + 'ID = ' + item.ID, 'Name = ' + item.name, "<br />" + 'Phone = ' + item.phone, "<br />" + 'Contact = ' + item.contact, "<br />" + 'BalanceLCY = ' + item.balanceLCY, "<br />" + 'CreditLimitLCY = ' + item.creditLimitLCY, "</li>")
}
})
.fail(function (jqXHR, textStatus, err) {
$('#RESULTS').text('Error: ' + err);
});
}
var options = {
url: "json.json",
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options);
</script>
</body>
</html>
you have
<input class="btn btn-default" id="buton" type="submit" value="search" onclick="find();" />
try
<button type="button" id="buton">Click me</button>
and
$("#buton").click(function () {
$("#list").remove();
//do more stuff
});
Related
I am working on jQuery homework again and I am having an issue getting my results to display for a search function using the Google Books API. I have a form getting a search term, number of max results to show along with the page to show. My page also has a section to display my GB Bookshelf, which is functioning as it should I am not getting errors in the Dev Tools console of Chrome and VS Code is not showing any errors. I took my search string and put it in Chrome and put in values for the variables to ensure I am getting results, which I am. I am sure I am missing something small that is escaping my eyes.
JS Code
/*jQuery code to show advanced search bar*/
/*Also hides advanced search link once clicked*/
$(document).ready(function(){
$("#advanced-search").hide();
$("#showAdvancedSearch").on('click',function(){
$("#advanced-search-show").hide();
$("#advanced-search").show();
});
});
/*begin bookshelf*/
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var gbaObject = JSON.parse(this.responseText);
var gbaHTML = '';
gbaObject.items.forEach(function (item) {
if (typeof item.volumeInfo.imageLinks != "undefined" && item.volumeInfo.imageLinks != null && item.volumeInfo.imageLinks != "") {
gbaHTML += `<div class="div200 border" onclick="singleGoogleBooks('` + item.id + `');">
<div>
<img src="` + item.volumeInfo.imageLinks.smallThumbnail + `" alt="` + item.volumeInfo.title + `" title="` + item.volumeInfo.title + `"/>
<div class="title"><strong>Title:</strong> ` + item.volumeInfo.title + `</div>
</div>
</div>`;
}
});
$('#displayBookshelf').html(gbaHTML);
}
};
xmlhttp.open("GET", "https://www.googleapis.com/books/v1/users/115951386289303716892/bookshelves/1001/volumes?startIndex=0&maxResults=10", true);
xmlhttp.send();
/*end bookshelf*/
/*begin booksearch*/
function bookSearch() {
var term = $("#q-term").val();
var maxResults = parseInt($("#maxResults").val());
var goToPage = parseInt($("#goToPage").val());
var startIndex = parseInt(goToPage) * parseInt(maxResults);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var gbaSearchObject = JSON.parse(this.responseText);
var gbaSearchHTML = '';
gbaSearchObject.items.forEach(function (item) {
if (typeof item.volumeInfo.imageLinks != "undefined" && item.volumeInfo.imageLinks != null && item.volumeInfo.imageLinks != "") {
gbaSearchHTML += `<div class="div200 border" onclick="singleGoogleBooks('` + item.id + `');">
<div>
<img src="` + item.volumeInfo.imageLinks.smallThumbnail + `" alt="` + item.volumeInfo.title + `" title="` + item.volumeInfo.title + `"/>
<div class="title"><strong>Title:</strong> ` + item.volumeInfo.title + `</div>
</div>
</div>`;
}
});
$('#displayBookResults').html(gbaSearchHTML);
}
};
xmlhttp.open("GET", "https://www.googleapis.com/books/v1/volumes?q=" + term + "&startIndex=" + startIndex + "&maxResults=" + maxResults + "", true);
xmlhttp.send();
return false;
}
/*end booksearch*/
/*send user to details page onclick of results (PDP)*/
function singleGoogleBooks(bid) {
window.location.href = '/single-google-books/?bid=' + bid + '';
}
/*end PDP*/
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lee Baldwin - Milestone 2</title>
<!--import external stylesheet-->
<link href="styles/main.css" rel="stylesheet" />
<!-- import jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!--import external javascript-->
<script src="scripts/main.js"></script>
</head>
<body>
<div class="header">
<h1>Lee Baldwin</h1>
<h3>Kennesaw State University Student</h3>
</div>
<div>
<ul>
<li>Milestone 1a</li>
<li>Milestone 1b</li>
<li>Milestone 2</li>
<li>Milestone 3</li>
<li>Milestone 4</li>
</ul>
</div>
<div class="search-bar">
<label for="searchForm">Keywords:</label>
<form method="post" action="javascript:;" id="searchForm" onsubmit="return bookSearch()">
<input type="text" id="q-term" required="required"/>
<button type="submit">Submit</button>
<span id="advanced-search-show">Advanced Search</span>
<span class="search-bar" id="advanced-search">
<label for="maxResults">Max Results:</label>
<select id="maxResults" onchange="bookSearch()">
<option>10</option>
<option>20</option>
<option>30</option>
<option>40</option>
</select>
<label for="goToPage">Go to Page:</label>
<select id="goToPage" onchange="bookSearch()">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
</select>
</span>
</div>
<h2>Search Results</h2>
<div class="grid-container" id="displayBookResults">
</div>
<h2>My Bookshelf</h2>
<div class="grid-container" id="displayBookshelf">
</div>
</body>
</html>
console.log
main.js:19 (5) [{…}, {…}, {…}, {…}, {…}]0: {kind: "books#volume", id: "eSIsAwAAQBAJ", etag: "vL5v8dEFNzc", selfLink: "https://www.googleapis.com/books/v1/volumes/eSIsAwAAQBAJ", volumeInfo: {…}, …}1: {kind: "books#volume", id: "LpctBAAAQBAJ", etag: "DoHITbafozc", selfLink: "https://www.googleapis.com/books/v1/volumes/LpctBAAAQBAJ", volumeInfo: {…}, …}2: {kind: "books#volume", id: "Wmfr1Zp7d5EC", etag: "R1DNX3Ho1hU", selfLink: "https://www.googleapis.com/books/v1/volumes/Wmfr1Zp7d5EC", volumeInfo: {…}, …}3: {kind: "books#volume", id: "PXa2bby0oQ0C", etag: "2NYLWaSh5Wc", selfLink: "https://www.googleapis.com/books/v1/volumes/PXa2bby0oQ0C", volumeInfo: {…}, …}4: {kind: "books#volume", id: "ptiYBAAAQBAJ", etag: "mpwwx7aWosM", selfLink: "https://www.googleapis.com/books/v1/volumes/ptiYBAAAQBAJ", volumeInfo: {…}, …}length: 5__proto__: Array(0)
I solved my own issue, but want to thank #Greg for his assistance. To solve the issue, I created the bookshelf code as its' own function, then used an onLoad trigger in the body tag to load it. I also made a couple of enhancements such as hiding the search results display until a search is performed.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lee Baldwin - Milestone 2</title>
<!--import external stylesheet-->
<link href="styles/main.css" rel="stylesheet" />
<!-- import jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!--import external javascript-->
<script src="scripts/main.js"></script>
</head>
<body onload="bookshelf()">
<div class="header">
<h1>Lee Baldwin</h1>
<h3>Kennesaw State University Student</h3>
</div>
<div>
<ul>
<li>Milestone 1a</li>
<li>Milestone 1b</li>
<li>Milestone 2</li>
<li>Milestone 3</li>
<li>Milestone 4</li>
</ul>
</div>
<div class="search-bar">
<label for="searchForm">Keywords:</label>
<form method="post" action="javascript:;" id="searchForm" onsubmit="return bookSearch()">
<input type="text" id="q-term" required="required"/>
<button type="submit">Submit</button>
<span id="advanced-search-show">Advanced Search</span>
<span class="search-bar" id="advanced-search">
<label for="maxResults">Max Results:</label>
<select id="maxResults" onchange="bookSearch()">
<option>10</option>
<option>20</option>
<option>30</option>
<option>40</option>
</select>
<label for="goToPage">Go to Page:</label>
<select id="goToPage" onchange="bookSearch()">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
</select>
</span>
</div>
<div class="grid-container" id="displayBookResults">
<h2>Search Results</h2>
</div>
<h2>My Bookshelf</h2>
<div class="grid-container" id="displayBookshelf">
</div>
</body>
</html>
JS
/*jQuery code to show advanced search bar*/
/*Also hides advanced search link once clicked*/
$(document).ready(function(){
$("#displayBookResults").hide();
$("#advanced-search").hide();
$("#showAdvancedSearch").on('click',function(){
$("#advanced-search-show").hide();
$("#advanced-search").show();
});
});
/*begin bookshelf*/
function bookshelf(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var gbaObject = JSON.parse(this.responseText);
var gbaHTML = '';
console.log(gbaObject.items);
gbaObject.items.forEach(function (item) {
if (typeof item.volumeInfo.imageLinks != "undefined" && item.volumeInfo.imageLinks != null && item.volumeInfo.imageLinks != "") {
gbaHTML += `<div class="div200 border" onclick="singleGoogleBooks('` + item.id + `');">
<div>
<img src="` + item.volumeInfo.imageLinks.smallThumbnail + `" alt="` + item.volumeInfo.title + `" title="` + item.volumeInfo.title + `"/>
<div class="title"><strong>Title:</strong> ` + item.volumeInfo.title + `</div>
</div>
</div>`;
}
});
$('#displayBookshelf').html(gbaHTML);
}
};
xmlhttp.open("GET", "https://www.googleapis.com/books/v1/users/115951386289303716892/bookshelves/1001/volumes?startIndex=0&maxResults=10", true);
xmlhttp.send();
}
/*end bookshelf*/
/*begin booksearch*/
function bookSearch() {
var term = $("#q-term").val();
var maxResults = parseInt($("#maxResults").val());
var goToPage = parseInt($("#goToPage").val());
var startIndex = parseInt(goToPage) * parseInt(maxResults);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var gbaSearchObject = JSON.parse(this.responseText);
var gbaSearchHTML = '';
console.log(gbaSearchObject.items);
gbaSearchObject.items.forEach(function (item) {
if (typeof item.volumeInfo.imageLinks != "undefined" && item.volumeInfo.imageLinks != null && item.volumeInfo.imageLinks != "") {
gbaSearchHTML += `<div class="div200 border" onclick="singleGoogleBooks('` + item.id + `');">
<div>
<img src="` + item.volumeInfo.imageLinks.smallThumbnail + `" alt="` + item.volumeInfo.title + `" title="` + item.volumeInfo.title + `"/>
<div class="title"><strong>Title:</strong> ` + item.volumeInfo.title + `</div>
</div>
</div>`;
}
});
$("#displayBookResults").show();
$('#displayBookResults').html(gbaSearchHTML);
}
};
xmlhttp.open("GET", "https://www.googleapis.com/books/v1/volumes?q=" + term + "&startIndex=" + startIndex + "&maxResults=" + maxResults + "", true);
xmlhttp.send();
return false;
}
/*end booksearch*/
/*send user to details page onclick of results (PDP)*/
function singleGoogleBooks(bid) {
window.location.href = '/single-google-books/?bid=' + bid + '';
}
/*end PDP*/
I am doing add and edit operation.
To perform edit operation I have used the below link for reference
and finished it. If I click the edit button I can see popup form with details. Now I have to call the funtion and should perform ajax call for both add and edit. But the URL for edit is different .How should I do it?Please refer my previous question
<html>
<head>
<title>
List of user
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add,Edit,Delete user</title>
<link href="/static/css/qxf2_scheduler.css" rel="stylesheet">
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet">
<link href="//resources/demos/style.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="dialog-confirm" title="Delete user?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These user will be
permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<div class="container col-md-offset-1">
<h2 class="grey_text text-center">user List</h2>
<input class="btn btn-info" type="button" id="create-user" value="Add user">
<div class="row-fluid top-space-20">
{% if result | length == 0 %}
<div>
<p>There are no user details ,If you want you can add it </p>
</div>
{% else %}
<table class="table table-striped">
<thead>
<th>user name</th>
<th>user duration</th>
<th>user Description</th>
<th>user requirements</th>
<th>Actions</th>
</thead>
{% for each_item in result %}
<tbody>
<td>{{each_item.user_name}}</td>
<td>{{each_item.user_time}}</td>
<td>{{each_item.user_description}}</td>
<td>{{each_item.user_requirement}}</td>
<td>
<input class="edituser btn btn-info" type="button" value="Edit" data-user-id = "{{each_item.user_id}}" data-user-name="{{each_item.user_name}}" data-user-description="{{each_item.user_description}}" data-user-requirement="{{each_item.user_requirement}}" data-user-duration="{{each_item.user_time}}">
<input type="button" class="btn btn-info" onclick="delete_user(this)" value="Delete"
id="delete-button{{each_item.user_id}}" data-delete-user-id="{{each_item.user_id}}"
data-delete-department-id="{{department_id}}" />
</td>
</tbody>
{% endfor %}
{% endif %}
</table>
</div>
</div>
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="username">user name</label>
<input type="text" name="username" id="username" class="text ui-widget-content ui-corner-all">
<label for="duration">Duration</label>
<input type="text" name="duration" id="duration" class="text ui-widget-content ui-corner-all">
<label for="description">Description</label>
<input type="text" name="description" id="description" class="text ui-widget-content ui-corner-all">
<label for="requirements">Requirements</label>
<input type="requirements" name="requirements" id="requirements"
class="text ui-widget-content ui-corner-all">
<input type="hidden" id='departmentId' ,value="{{department_id}}">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$(function () {
var dialog, form,
username = $("#username"),
duration = $("#duration"),
description = $("#description"),
requirements = $("#requirements"),
allFields = $([]).add(username).add(duration).add(description).add(requirements),
tips = $(".validateTips");
function updateTips(t) {
console.log(t);
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function addUser(url,msg) {
var valid = true;
allFields.removeClass("ui-state-error");
var username = $("#username");
var duration = $("#duration");
var description = $("#description");
var requirements = $("#requirements");
var departmentId = document.getElementById("departmentId").value;
valid = valid && checkLength(username, "username", 3, 16);
valid = valid && checkLength(duration, "duration", 3, 16);
valid = valid && checkLength(description, "description", 3, 300);
valid = valid && checkLength(requirements, "requirments", 5, 300);
console.log(url,msg);
if (valid) {
var username = $("#username").val();
var duration = $("#duration").val();
var description = $("#description").val();
var requirements = $("#requirements").val();
var departmentId = document.getElementById("departmentId").value;
$("#users tbody").append("<tr>" +
"<td>" + username + "</td>" +
"<td>" + duration + "</td>" +
"<td>" + description + "</td>" +
"<td>" + requirements + "</td>" +
"</tr>");
$.ajax({
type: 'POST',
url: url,
data: {
'username': username,
'duration': duration,
'description': description,
'requirements': requirements
},
success: function (result) {
console.log(result);
alert(msg);
document.location.href = "/departments";
},
})
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
var url = '/department/%d/user'%departmentId;
var msg = 'The user has been added'
addUser(url,msg);
});
editDialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Edit user": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
var url = '/department/%d/user/edit'%departmentId;
var msg = 'The user has been edited'
addUser(url,msg);
});
$("#create-user").button().on("click", function () {
console.log("I am first");
dialog.dialog("open");
});
$(".edituser").button().on("click", function () {
var id = $(this).attr("data-user-id");
var userName=$(this).attr("data-user-name");
var userDuration=$(this).attr("data-user-duration");
var userDescription=$(this).attr("data-user-description");
var userRequirements=$(this).attr("data-user-requirement");
console.log(id,userName);
$("#username").val(userName);
$("#duration").val(userDuration);
$("#description").val(userDescription);
$("#requirements").val(userRequirements);
editDialog.dialog("open");
});
});
</script>
<script>
//Confirmation message for deleteing user
var user_id;
var department_id;
var dialog = $("#dialog-confirm").dialog({
resizable: false,
height: "auto",
autoOpen: false,
width: 400,
modal: true,
buttons: {
"Delete": function () {
console.log("user_id" + user_id)
$.ajax({
type: 'GET',
url: '/user/' + user_id + '/departments/' + department_id + '/delete',
data: { 'user_id': user_id },
success: function (data) {
window.location.reload();
console.log("successfully deleted the data")
}
})
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
function delete_user(action_delete) {
user_id = action_delete.getAttribute("data-delete-user-id");
department_id = action_delete.getAttribute("data-delete-department-id");
dialog.dialog("open");
}
</script>
</body>
</html>
By Making the common function for the Ajax:
function doAjaxCall(var url,var data,var method,var callBackFunction)
{
$.ajax({
type: method,
url: url,
data: data,
success: function(data){
callBackFunction(data);
}
});
}
Call the Function like this
function onAdd(data){
// Code to append
}
doAjaxCall("/add",userData,"POST",onAdd);
function onEdit(data){
// Code to update
}
doAjaxCall("/update",userData,"PUT",onEdit);
Store your url in a string variable. Depends on add/edit button onClick, change the url string of that variable and pass that variable in ajax call url attribute.
How can I display my data into another html after submit? I tried to store the value in local Storage and that didn't work out. How can i display the result in other page? In the below snippet i some how achieved to display data by using show and hide methods. But i'm looking to display my data in new HTML page.
var data = [
{
"username": "MADHU BABU POOJALA",
"skills": "BD",
"location": "Hyderabad",
"email": "rgw#yahoo.in",
"bscore": 856,
"ranking": 14652,
},
{
"username": "Mj",
"skills": ".net",
"location": "Hyderabad",
"email": "csaca#yahoo.in",
"bscore": 8540,
"ranking": 1452,
}
];
var result = [];
function Sort(val) {
result.sort(function (a, b) {
if (a[val] < b[val]) return -1;
if (a[val] > b[val]) return 1;
return 0;
});
searchResult(result);
}
function search(str) {
var str = str.trim().toUpperCase();
if (str !== '') {
var rslt = [];
for (var j = 0; j < result.length; j++) {
if (result[j].skills.toUpperCase().match(str)) {
rslt.push(result[j]);
}
}
searchResult(rslt);
} else {
searchResult(result);
}
}
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '',
location = $("#location").val() || '',
i;
result = []
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]
["email"].toUpperCase() === email.toUpperCase()) || (data[i]["location"].toUpperCase() ===
location.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
$(".ip").hide();
$(".tb").show();
var output = getResult();
searchResult(output);
});
$("#back").click(function () {
$('input[type="text"]').val('').removeAttr('checked').removeAttr('selected');
$('input[type="email"]').val('').removeAttr('checked').removeAttr('selected');
$(".tb").hide();
$(".ip").show();
});
function searchResult(output) {
var html = '';
$.each(output, function (key, value) {
html += '<div style="border:1px solid #000;padding:10px;margin:10px;">';
html += '<span style="font-weight:bold;">' + value.username + '</span>' +
'<br/>';
html += '<span>' + 'Email :' + '</span>' + '<span>' + value.email + '</span>' +
'<br/>';
html += '<span>' + 'Skills :' + '</span>' + '<span>' + value.skills + '</span>' +
'<br/>';
html += '<span>' + 'Location :' + '</span>' + '<span>' + value.location + '</span>' +
'<br/>';
html += '<span>' + 'B-score :' + '</span>' + '<span>' + value.bscore + '</span>' +
'<br/>';
html += '<span>' + 'Ranking :' + '</span>' + '<span>' + value.ranking + '</span>' +
'<br/>';
html += '</div>';
});
$('#table').html(html);
}
$(document).ready(function () {
$('#submit').attr('disabled', 'disabled');
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$('input[type="submit"]').removeAttr('disabled');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU"
crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
.results tr[visible='false'],
.no-result {
display: none;
}
.results tr[visible='true'] {
display: table-row;
}
.form-group {
position: fixed;
top: 30%;
left: 50%;
width: 1200px;
height: 200px;
background: #fff;
transform: translate(-15%, -50%);
}
</style>
</head>
<body>
<div class="ip">
<div class="form-group ">
<div class="col-4">
<label for="skills">Skills</label>
<input class="form-control" id="skills" type="text" placeholder="skills">
</div>
<div class="col-4">
<label for="email">Email</label>
<input class="form-control" id="email" type="text" placeholder="mail id">
</div>
<div class="col-4">
<label for="username">Username</label>
<input class="form-control" id="username" type="text" placeholder="username">
</div>
<div class="col-4">
<label for="location">location</label>
<input class="form-control" id="location" type="text" placeholder="location">
</div>
<br>
<div class="col-4">
<input id="submit" class="btn" type="submit" value="submit" disabled='disabled'>
</div>
</div>
</div>
<br>
<div style="display: none" class="tb">
<button class="btn" id="back">back to search</button>
<br>
<br>
<br>
<div class="container-fluid">
<div class="row">
<div class="left">
<label style="font-size: 20px;color: black;margin:0px">
Core Skills :
</label>
<input type="text" onkeyup="search(this.value)">
</div>
<div class="right">
<form>
<label style="font-size: 20px;color: black;margin:0px">
Sort By :
</label>
<select onchange="Sort(this.value)">
<option>-- select --</option>
<option value="username">A to Z</option>
<option value="bscore">B-score</option>
<option value="ranking">Ranking</option>
</select>
</form>
</div>
</div>
</div>
<div id="table">
</div>
</div>
</body>
</html>
I want to copy the contents of a textbox of a particular div into another div.
I am looping through a products array which contains all the products and then I am checking with parentChildMapping to see if that product has children or not.
If we are entering values for min, max, typ and then adding a child then I want all those values which we entered for min, max, typ to be copied.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-theme.min.css">
<script src="jquery-2.2.5.min.js" type='text/javascript'></script>
<script src="bootstrap.min.js" type='text/javascript'></script>
<script src="angular.min.js" type='text/javascript'></script>
<script src="parent_child_mapping.js" type='text/javascript'></script>
<script src="products.js" type='text/javascript'></script>
<script src="app.js" type='text/javascript'></script>
<script src="indexController.js" type='text/javascript'></script>
<style>
.clsProductDetailsHldr .well
{
padding-top: 5px;
padding-bottom: 5px;
margin-bottom: 4px;
}
.inputError
{
border: 1px solid red;
background-color: antiquewhite;
}
.row
{
margin-bottom: 4px;
}
</style>
</head>
<body ng-app="productspoc">
<div ng-controller="indexCtrl">
<div class="container clsProductDetailsHldr">
<div ng-repeat="product in products track by $index">
<div class="well" ng-class="{'col-sm-6':!checkIfProductHasChildren(product)}">
<div class="row">
<span class="" ng-class="{'col-sm-10':checkIfProductHasChildren(product),'col-sm-4':!checkIfProductHasChildren(product)}">{{product}}</span>
<span class="col-sm-4" ng-if="!checkIfProductHasChildren(product)">
<input type="text" value="" ng-model="productsObj[''+product]" />
</span>
<span class="col-sm-2" ng-if="checkIfProductHasChildren(product)">
<input type="button" class="btn" value="Add Child" ng-click="addChildToParent(product)" />
</span>
</div>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-11">
<span class="col-sm-10" ng-if="checkIfNewChild(product,key)">
<input type="button" class="btn" value="Remove Child" ng-click="removeChildFromParent(product, key)" />
</span>
<div class="col-sm-4" ng-if="checkIfProductHasChildren(product)" ng-repeat="(key1, value1) in productsObj[''+product] track by $index">
<span class="col-sm-2">{{key1}}</span>
<span class="col-sm-2">
<input type="text" ng-focus="onInputFocus($event)" value="" ng-model="productsObj[''+product][''+key1]" />
</span>
</div>
</div>
</div>
</div>
</div>
<div class="row" style="text-align:center;">
<span>
<input type="button" value="clear" class="btn btn-primary" ng-click="onClearClick()" />
</span>
<span>
<input type="button" value="Save" class="btn btn-success" ng-click="onSaveClick()" />
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(".clsAddChild").click(function()
{
var newChild = "";
newChild+= '<div class="row">';
newChild+= '<div class="col-sm-12" style="padding-left:20px;"><span>NewChild Child 1</span></div>';
newChild+= '</div>';
newChild+= '<div class="row">';
newChild+= '<div class="col-sm-12" style="padding-left:25px;"><span>NewChild Child 1 child 1</span><span><input type="text" /></span></div>';
newChild+= '<div class="col-sm-12" style="padding-left:25px;"><span>NewChild Child 1 child 2</span><span><input type="text" /></span></div>';
newChild+= '<div class="col-sm-12" style="padding-left:25px;"><span>NewChild Child 1 child 3</span><span><input type="text" /></span></div>';
newChild+= '<div class="col-sm-12" style="padding-left:25px;"><span>NewChild Child 1 child 4</span><span><input type="text" /></span></div>';
newChild+= '<div class="col-sm-12" style="padding-left:25px;"><span>NewChild Child 1 child 5</span><span><input type="text" /></span></div>';
newChild+= '</div>';
$(this).closest(".parentChildWrapper").append(newChild);
});
</script>
</body>
</html>
indexController.js
angular.module('productspoc')
.controller('indexCtrl',['$scope', function ($scope) {
$scope.productsObj = {};
$scope.products = products;
$scope.parentChildMapping = parentChildMapping;
$scope.checkIfProductHasChildren = function(product)
{
return product in $scope.parentChildMapping;
};
$scope.addChildToParent = function(parent)
{
var porductIndex = products.indexOf(parent);
products.splice(porductIndex + 1, 0, parent + 1);
$scope.parentChildMapping[parent +1]= parent + 1;
$scope.productsObj[""+parent +1]= {"Min": "","Typ":"","Max": ""};
console.log($scope.productsObj);
};
$scope.checkIfNewChild = function(product,key)
{
if(( product.indexOf("1") ===2 || product.indexOf("1") ===3 ||product.indexOf("1") ===4))
return true;
else
return false;
};
$scope.removeChildFromParent = function(product, key)
{
delete $scope.productsObj[""+product];
var porductIndex = products.indexOf(product);
products.splice( porductIndex, 1 );
};
$scope.onClearClick = function()
{
var r=confirm("Are you sure, wanted to reload the page. If yes then click on OK, else Cancel and resume your work.");
if (r==true){
window.location.reload();
angular.element(".clsProductDetailsHldr input[type='text']").val("");
}
else{
}
};
$scope.validateNumberFields = function()
{
var isValid = true;
angular.forEach(angular.element(".clsProductDetailsHldr .onlyNumbers"), function(value, index){
if(isNaN(angular.element(value).val()))
{
isValid = false;
angular.element(value).addClass("inputError");
}
});
return isValid;
};
$scope.onInputFocus = function(event)
{
angular.element(event.currentTarget).removeClass("inputError");
};
$scope.onSaveClick = function()
{
var isValid = $scope.validateNumberFields();
if(!isValid)
{
alert("Selected Input feild has invalid number");
return;
}
angular.forEach($scope.productsObj, function(value, key){
if(value instanceof Object && value.hasOwnProperty('newChildCount'))
delete value.newChildCount;
if(value instanceof Object)
{
angular.forEach(value, function(value1, key1)
{
// Below code will check
// key1 should not be a Note and value1 should have some value
if(key1!=='Note' && value1)
{
console.log(value1.length)
var pram = value1.substring(value1.length-1, value1.length);
switch (pram)
{
case "n":
value1 = (value1.substring(0,value1.length-1))*.000000001;
break;
case "p":
value1 = (value1.substring(0,value1.length-1))*.000000000001;
break;
case "m":
value1 = (value1.substring(0,value1.length-1))*.001;
break;
case "u":
value1 = (value1.substring(0,value1.length-1))*.000001;
break;
case "k":
value1 = (value1.substring(0,value1.length-1))*1000;
break;
case "M":
value1 = (value1.substring(0,value1.length-1))*1000000;
break;
case "G":
value1 = (value1.substring(0,value1.length-1))*1000000000;
break;
default:
value1;
break;
}
$scope.productsObj[key][key1] = value1 ;
console.log(pram);
}
console.log(value1);
});
}
});
console.log(JSON.stringify($scope.productsObj));
console.log($scope.productsObj);
var sub=confirm("Data will be saved on click of OK button.");
if (sub==true)
{
$.ajax({
url: "/rest/products/add/",
type: "POST",
dataType: "json", // expected format for response
contentType: "application/json", // send as JSON
data: JSON.stringify($scope.productsObj),
complete: function() {
$window.location.href = "#/success.html";
alert( "Data saved to database: " + data );
console.log('success response' + response)
},
success: function(data) {
$window.location.href = "#/success.html";
alert( "Data saved to database: " + data );
console.log('success response' + response)
},
error: function() {
//called when there is an error
},
});
}
else
{
}
};
$scope.initProductDetails = function()
{
for(var i=0;i<$scope.products.length;i++)
{
if($scope.products[i] in parentChildMapping)
{
$scope.productsObj[""+$scope.products[i]] = {};
$scope.productsObj[""+$scope.products[i]].newChildCount = 0;
$scope.productsObj[""+$scope.products[i]] = {"Min": "","Typ":"","Max": ""};
}
else
$scope.productsObj[""+products[i]] = "";
}
};
$scope.initProductDetails();
}]);
products.js
products = [
"Part_Number",
"Name",
"Code",
"absmax_1",
"absmax_2",
"absmax_3",
"absmax_4"
]
parent_Child_Mapping.js
parentChildMapping ={
"absmax_1":"absmax_1",
"absmax_2":"absmax_2",
"absmax_3":"absmax_3",
"absmax_4":"absmax_4",
}
You can put all elements he wants to clone in a div and clone that whole div. Below is an small sample code showing such behavior:
<html>
<head>
<script>
function cloneMe(){
var tT = document.querySelectorAll('.Content > div'); //All the div inside .Content;
var tL = tT[tT.length - 1]; //The last div - the one to get copied
var tC = tL.cloneNode(true);// Deep cloning the last div 'tL'
tL.parentNode.appendChild(tC) //Adding the copy to the parent of the last div 'tL'
}
</script>
</head>
<body>
<button onclick = 'cloneMe()'>Add</button>
<div class = 'Content'>
<div>
<input name = 'min' type = 'text' placeholder = 'min' />
<input name = 'typ' type = 'text' placeholder = 'typ' />
<input name = 'max' type = 'text' placeholder = 'max' />
</div>
</div>
</body>
</html>
I'm trying to convert this javascript DOM into jquery, and my code isn't running for some reason. This is the DOM I am using.
document.getElementById("forma").onsubmit = function () {
var ime = document.getElementById("ime").value;
var priimek = document.getElementById("priimek").value;
var stranka = document.getElementById("stranka").value;
try {
var kandidat = Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
document.getElementById("seznam").innerHTML = OblikujIzpis(PridobiPolje());
document.getElementById("obvestila").innerHTML = "Uspešen Vnos!";
document.getElementById("obvestila").className = "bg-success";
}
catch (napaka) {
document.getElementById("obvestila").innerHTML = napaka.message;
document.getElementById("obvestila").className = "bg-danger";
}
document.getElementById("forma").reset();
}
document.getElementById("forma_isci").onsubmit = function () {
var iskani_niz = document.getElementById("iskalniNiz").value;
document.getElementById("seznam").innerHTML = OblikujIzpis(Isci(iskani_niz));
document.getElementById("obvestila").innerHTML = "Rezultat iskanja po iskalnem nizu " + iskani_niz;
document.getElementById("obvestila").className = "bg-info";
}
document.getElementById("pobrisi").onclick = function () {
IzbrisiPolje();
document.getElementById("obvestila").innerHTML = "Polje je bilo izbrisano!";
document.getElementById("obvestila").className = "bg-success";
document.getElementById("seznam").innerHTML = "";
document.getElementById("forma").reset();
}
This is what I tried writing in jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("forma").submit(function(){
var ime=$("ime").val();
var priimek=$("priimek").val();
var stranka=$("stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("seznam").html(OblikujIzpis(PridobiPolje());
$("obvestila").html("Uspešen Vnos!");
$("obvestila").addClass("bg-success");
}
catch(napaka){
$("obvestila").html(napaka.message);
$("obvestila").addClass("bg-danger");
}
$("forma").reset();
$("forma_isci").submit=function(){
var iskani_niz=$("iskaniNiz").val();
$("seznam").html(OblikujIzpis(iskani_niz));
$("obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("obvestila").addClass("bg-info");
}
$("pobrisi".click=function(){
IzbrisiPolje();
$("obvestila").html("Polje je bilo izbrisano!");
$("obvestila").addClass("bg-success");
$("seznam").html("");
$("forma").reset();
}
}
});
});
</script>
here is my HTML file
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="funkcije.js"></script>
<script src="dom.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>JavaScript - DOM</title>
</head>
<body>
<div class="container">
<h1>Seznam predsedniških kandidatov!</h1>
<form action="#" id="forma_isci" class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="iskalniNiz" placeholder="Iskalni niz">
</div>
<button type="submit" class="btn btn-info">Išči</button>
</form>
<br />
<br />
<h3>Vnos novih kandidatov</h3>
<form action="#" id="forma" class="form-group">
<table class="table">
<tr>
<td>Ime:</td>
<td>
<input type="text" id="ime" placeholder="Ime kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Priimek:</td>
<td>
<input type="text" id="priimek" placeholder="Priimek kandidata" class="form-control" />
</td>
</tr>
<tr>
<td>Stranka:</td>
<td>
<select id="stranka" class="form-control" >
<option>Demokratska</option>
<option>Republikanska</option>
<option>Neodvisna</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Dodaj" class="btn btn-info" />
</td>
<td>
<input type="reset" value="Ponastavi" class="btn btn-info" />
</td>
</tr>
</table>
</form>
<br />
<br />
<p id="obvestila"></p>
<br />
<br />
<h3>Seznam obstoječih kandidatov</h3>
<ul id="seznam" class="list"></ul>
<button class="btn" id="pobrisi">Pobriši seznam</button>
</div>
</body>
</html>
So anyway, I'm not going to post the functions here since they're not needed to be seen here.
The javascript code works, the site works then and the elements get added normally. But I would like to have the same effect but written in Jquery. I think some of the issues are in .className, which I replaced with .Addclass from jquery and .innerHTML where I write .html(function). If someone could convert this for me it would be great, since I am kinda new to jquery I'm having some issues.
update n1*
changed the Jquery to this
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$(document).ready(function(){
$("#forma").submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").myClass("bg-success");
}
catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").myClass("bg-danger");
}
$("#forma").reset();
}
$("#forma_isci").submit=function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").myClass("bg-info");
}
$("#pobrisi".click=function(){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").myClass("bg-success");
$("#seznam").html("");
$("#forma").reset();
}
}
});
});
</script>
Added the # where there's an ID, and changed .addClass to .myClass. Add function is still not working. But some other functions are working.
The functions.
var polje = [];
function Kandidat(ime, priimek, stranka) {
if (ime ==="" || priimek === "") {
throw new Error("Podatki niso popolni!");
}
else {
var id = polje.length + 1;
var oseba = {id:id, ime:ime, priimek:priimek, stranka:stranka};
oseba.Izpis = function () {
return "(" + this.id + ")" + this.ime + " " + this.priimek + " pripada stranki " + this.stranka;
}
return oseba;
}
}
function DodajKandidataNaPolje(kandidat) {
polje.push(kandidat);
return true;
}
function PridobiPolje() {
return polje;
}
function OblikujIzpis(polje) {
var izpis = "";
for (var i = 0; i < polje.length; i++) {
izpis = izpis + "<li>" + polje[i].Izpis() + "</li>";
}
return izpis;
}
function Isci(iskalniNiz) {
var rezultat = [];
var oseba;
var vsebuje;
for (var i = 0; i < polje.length; i++) {
oseba = polje[i];
vsebuje = oseba.ime.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.priimek.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
else{
vsebuje = oseba.stranka.search(iskalniNiz);
if (vsebuje != -1) {
rezultat.push(oseba);
}
}
}
}
return rezultat;
}
function IzbrisiPolje() {
polje = [];
return true;
}
in jQuery, in order to access an element, you need to use a selector. In your case, the form has an id of forma (which in jQuery selectors, you prefix it with #). In order to access your form, you need to do the following:
change this:
$("forma").submit(function(){
to this:
$("#forma").submit(function(){
Anywhere else you use jQuery to access an element in your code would have to be changed as well. use #myid for ids, .myclass for classes. See this for more information.
Here is your code (jQuery section only) with some things fixed:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var forma = $('#forma');
forma.submit(function(){
var ime=$("#ime").val();
var priimek=$("#priimek").val();
var stranka=$("#stranka").val();
try{
var kandidat= Kandidat(ime, priimek, stranka);
DodajKandidataNaPolje(kandidat);
$("#seznam").html(OblikujIzpis(PridobiPolje());
$("#obvestila").html("Uspešen Vnos!");
$("#obvestila").addClass("bg-success");
} catch(napaka){
$("#obvestila").html(napaka.message);
$("#obvestila").addClass("bg-danger");
}
forma[0].reset();
});
$("#forma_isci").submit(function(){
var iskani_niz=$("#iskaniNiz").val();
$("#seznam").html(OblikujIzpis(iskani_niz));
$("#obvestila").html("Rezultat iskanja po iskalnem nizu " + iskani_niz);
$("#obvestila").addClass("bg-info");
});
$("#pobrisi").click(function( ){
IzbrisiPolje();
$("#obvestila").html("Polje je bilo izbrisano!");
$("#obvestila").addClass("bg-success");
$("#seznam").html("");
forma[0].reset();
});
});
</script>