I have a text box and a button. On the button . click function the name appears but I want id (that the user enters into the text box for the corresponding name to appear)
this is a snip from the json:
{"user":[{"ID" : "001","name": "Zara Ali"}]}
This is the button/text ( that i have inside an alert div because i think it looks cool in my page and works with the .click)
<div class="alert alert-info">
<input type="text" id="userName" value>
<button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button>
</div>
and this is the js i have used for the .click
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
$('#details').html('<p> Name: ' + jd.name + '</p>');
});
});
});
the result is going inside:
<div id = "details">
</div>
Try this:
$(document).ready(function() {
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#details').html('<p> Name: ' + jd.user[i].name + '</p>');
}
}
});
});
});
Related
I'm trying to build a wikipedia viewer using Wikipedia's API, but I have a minor problem. If I manually press the search button, everything works fine, but if I press enter, nothing happens. Here's the js code:
$(document).ready(function () {
$("#input").keyup(function (event) {
if (event.keyCode == 13) {
$("#submit-button").click();
}
});
});
function wikiSearch() {
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function (data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function (page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').html(html);
}
});
}
And here's the html code:
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form>
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
</form>
Random page
<input id="submit-button" type="button" value="Search" onclick="wikiSearch()" class="btn btn-success">
<div id="display"></div>
</div>
Here's a jsfiddle: https://jsfiddle.net/tbgoy836/
Replace input type="button" to submit. Also the input type="submit" should be inside the form. In that case you don't need to check the keycode & preventDefault will prevent the default behaviour of the form submit, since form is getting submitted using ajax. On pressing enter/return it will find the first submit button by itself and will trigger a click action
$(document).ready(function() {
$("#searchForm").submit(function(e) {
e.preventDefault();
wikiSearch()
})
});
function wikiSearch() {
console.log('wikiSearch')
var query = document.getElementById("input").value;
var wiki_api = 'https://en.wikipedia.org/w/api.php';
var api = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exlimit=max&format=json&exsentences=1&exintro=&explaintext=&generator=search&gsrlimit=10&gsrsearch=";
var wikilink = 'http://en.wikipedia.org/?curid=';
var link = api + query;
var html = "";
$.ajax({
url: link,
type: "get",
dataType: "JSONP",
success: function(data) {
var results = data.query.pages;
var pgs = Object.keys(results);
pgs.forEach(function(page) {
var title = results[page].title;
var text = results[page].extract;
var pagelink = wikilink + results[page].pageid;
html += '' + '<div class="item">' + title + '<br>' + '<p class="description-text" >' + text + '</p>' + '</div> <br> ';
});
$('#display').append(html);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="content">
<h1>Wikipedia Viewer</h1>
<form id="searchForm">
<input type="text" name="search" placeholder="Search Wikipedia" id="input">
<div>
Random page
<input id="submit-button" type="submit" value="Search" onclick="wikiSearch()" class="btn btn-success">
</div>
</form>
<div id="display"></div>
</div>
Why you don't call function in javascript?
$("#submit-button").click(function(){
wikiSearch();
})
And remove onclick parameter of input.
Try $("#submit-button").trigger("click");
Or
you can simply call the function wikiSearch() instead of trigger the click event of submit button
I am dynamically generating checkboxes from my database using jquery ajax to call my web api. The problem is that I am trying to get the length of the checkbox array but constantly receiving an array length of zero when i debug. Please what might be wrong with my code.
HTML CODE
<div class="panel-body">
<form method="post">
<div class="form-group">
<label>Add Role Name</label>
<input type="text" class="form-control" placeholder="Role Name" />
</div>
<div class="col-md-6">
<div class="well">
<fieldset id="appName">
</fieldset>
</div>
<input id="saveUrl" type="button" value="Add Role" class="btn btn-success pull-right" />
</div>
</form>
</div>
JQUERY CODE
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: 'GET',
url: 'http://localhost:61768/api/users/GetUrls',
headers: {
'Authorization': 'Basic ' + btoa(localStorage.getItem('ApplicationId') + ":" + localStorage.getItem('ApiKey'))
},
success: function (data) {
if (Object.keys(data).length == 0) {
alert("Ewoo");
} else {
$.each(data, function (index, value) {
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
$('#appName').append(input); //Where I generate the checkboxes
});
}
},
error: function () {
alert("DonDy");
}
});
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
$('#saveUrl').click(function () {
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
});
</script>
The result of click the save button is alerting bad
In this code checkbox is getting appended but you are not checking the checkbox
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
Here you are checking length of checked checkbox..hence alerting to bad :
var $checkboxes = $('input[name="chk[]"]:checked');
Try this and that to inside save url click fucntion:
$('#saveUrl').click(function () {
var $checkboxes = $('input[name="chk[]"]');
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
Since you are populating/creating checkbox inside an AJAX call, you should have $checkboxes inside the #saveUrl function, because before that, it would be empty when the JS is loaded. You need this variable when the #saveUrl is clicked, hence it should check for the checked inputs when the #saveUrl is triggered:
$('#saveUrl').click(function() {
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
I want to be able to add jquery UI to the list on GoalNotes This table gets populated by what the user enters in the "name1" and "data1" input fields. Every time I give the an id, the program breaks and I get no errors. Any ideas on how I could apply animations to the table rows that get added after the user inputs data?
html
<section class="section section--active color1" data-letter="M">
<article class="section__wrapper">
<h1 class="section__title">Monday</h1>
<div id="Monday" class="tabcontent">
<form name="goalsList1" action = "/created" method="POST">
<div id="tab1">
<table>
<tr>
<td><b>New Goal:</b><input type="text" name="name1" id="name1"></td>
<td><b>Notes:</b><input type="text" name="data1" id="data1"></td>
<td>
<input type="submit" value="Save" onclick="SaveItem(1)">
</td>
</tr>
</table>
</div>
<div id="items_table1">
<h2>List of goals</h2>
<table id="list1" contenteditable> </table>
<p>
<label><input type="button" value="Clear" onclick="ClearAll(1)"></label>
</p>
</div>
</form>
</div>
</article>
</section>
javascript
function doShowAll(numOfWeek) {
if (CheckBrowser()) {
var key = "";
var list = "**<tr><th>Goal</th><th>Notes</th></tr>**\n";
var i = 0;
var goals = localStorage[numOfWeek] ? JSON.parse(localStorage[numOfWeek]) : {};
var goalsKeys = Object.keys(goals);
for (i = 0; i < goalsKeys.length; i++) {
key = goalsKeys[i];
list += "<tr><td>" + key + "</td>\n<td>"
+ goals[key] + "</td></tr>\n";
}
if (list == "<tr><th>Goal</th><th>Notes</th></tr>\n") {
list += "<tr><td><i>nothin' here</i></td>\n<td><i>nothin' here either</i></td></tr>\n";
}
document.getElementById('list'+numOfWeek).innerHTML = list;
} else {
alert('Cannot store list as your browser do not support local storage');
}
}
$(document).ready(function(e) {
$('#due-date').datepicker();
$('#add-todo').button({
icons: {
primary: "ui-icon-circle-plus"
}
}).click(function() {
$('#new-todo').dialog('open');
}); // end click
$('#new-todo').dialog({
modal: true,
autoOpen: false,
close: function() {
$('#new-todo input').val(''); /*clear fields*/
},
buttons : {
"Add task" : function() {
var taskName = $('#task').val();
var dueDate = $('#due-date').val();
var beginLi = '<li><span class="done">%</span><span class="delete">x</span>';
var taskLi = '<span class="task">' + taskName + '</span>';
var dateLi = '<span class="due-date">' + dueDate + '</span>';
var endLi = '</li>';
$('#todo-list').prepend(beginLi + taskLi + dateLi + endLi);
$('#todo-list').hide().slideDown(250).find('li:first')
.animate({
'background-color': '#ff99c2'
},250)
.animate({
'background-color': '#d9b3ff'
},250).animate; // end animate
$(this).dialog('close');
},
"Cancel" : function() {
$(this).dialog('close');
}
}
});
$('#todo-list').on('click','.done',function(e) {
var $taskItem = $(this).parent("li");
var $copy = $taskItem.clone();
$('#completed-list').prepend($copy);
$copy.hide().slideDown();
$taskItem.remove();
}
); // end on
$('#todo-list, #completed-list').on('click','.delete',function(e) {
$(this).parent("li").slideUp(250, function() {
$(this).remove();
}); // end slideup
}); // end on
$('#todo-list').sortable();
}); // end ready
http://jsbin.com/digefufeca/edit?html,css,js,console,output
The problem
The form with nane goalsList1 is sending whenever you click on the button.
Why? because the button is submit button.
The solution(s)
Replace the button's type to button. (link)
Prevent the form submission by event.preventDefault(). (link)
There are more ways but those are the major.
Note: your code still not working but now you can see the error message.
I have a button and text box that reads an id for a specific user on my json file. If the user enters 001 their name will appear on the alert, the alert is hidden on page load but when the user enters this information the alert shows - Welcome (users name and details from the json file)
This script works, however when I wait a few seconds it disappears, how so I get it to stay on the page when it appears?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
$('#contact').fadeIn('slow');
});
}
}
});
}); });
also is there any way to add like a slide down or slide up animation when he alert box appears?
Alert box:
<div class="alert alert-success" id="loginalert"> <strong>Welcome!</strong></div>
The login box that requires the user to enter their ID:
div class="alert alert-info">
<input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
this now works if i take away the fade out
Is there any way to display the message
<div class="alert alert-danger">
<strong>Danger!</strong> Indicates a dangerous or potentially negativeaction.</div>
if a user enters an invalid id or enters nothing?
many thanks
Remove the fadeOut() part. That code is responsible for hiding it again.
$(function() {
//Hide alert when page loads
var alertBox=$("#loginalert");
alertBox.hide();
$("#loginbtn").on('click',function(e){
// console.log("clicked login");
e.preventDefault();
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
// console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
// show the alert if d.user[i].ID is idafter
var message= "<p> Welcome: ' + jd.user[i].name + '</p>'";
alertBox.html(message).fadeIn('slow',function(){
$('#contact').fadeIn('slow')
})
} else {
// show the alert if d.user[i].ID is not idafter
var message= "<p> Error </p>'";
alertBox.html(message).fadeIn('slow')
}
}
})
})
});
I have a simple log in at the top of my page, when the user enters their id thats on my json file their name appears in a welcome alert(the welcome alert is avaiable on ready and the name appears inside when the user logs in). I want the alert to be hidden but when the users enters their code (there is no username just a code) this alert appears with the name.
Here is the log in text and button:
<div class="alert alert-info"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
Here is the alert:
<div class="alert alert-success" id="loginalert"<strong>Welcome</strong></div>
and here is the js getting the corresponding name to appear:
$(document).ready(function() {
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
}
}
});
}); });
the json file includes the users id (which is the code for now) : 001
and their name
when the code is entered to the login text box their name appears on the page to indicate what user has logged in
I also wanted to know.. if there was no corresponding id to the four i have included in my json is there any way to get this alert to appear instead of the login alert, this would be like a you have entered an invalid code -
<div class="alert alert-danger"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
(also to be hidden on page load/ready)
Can anyone help out guys please?
Kind regards
Try this: I have modified your script.
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function () {
$('#contact').fadeIn('slow');
});
}
}
});
});
});
For Error Message try:
Modify your div to this,
<div class="alert alert-danger" id="ErrorMessageAlert"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
Thereafter modify your scripts again to this:
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#ErrorMessageAlert").hide();
$("#loginbtn").click(function(event){
//console.log("clicked login");
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
//console.log(id);
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
//show the alert after loading the information
$("#loginalert").show();
}else
{
$("#ErrorMessageAlert").show();
}
);
}
}
});
});
});
You can make your both alert forms hidden by default by adding hidden class and then through query show()-http://api.jquery.com/show/ display needed one
<style>
.hidden{
display:none;
}
</style>
<div class="alert alert-info hidden"><input type="text" id="userName" value> <button type="button" id="loginbtn" class="btn btn-primary btn-md">Login</button></div>
<div class="alert alert-danger hidden"> <strong>Danger!</strong> Indicates dangerous or potentially negative action.</div>
<script>
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
// Defined to keep if match found in loop
var matchFound = false;
for (var i=0; i<jd.user.length; i++) {
if (jd.user[i].ID == id) {
$('#loginalert').html('<p> Welcome: ' + jd.user[i].name + '</p>');
// Show Welcome alert
$(".alert-info").show();
matchFound = true;
break;
}
}
// which means no match found and matchFound is not equal to true
if( !matchFound ){
// Show Error alert
$(".alert-danger").show();
}
});
</script>