I am currently practicing making Ajax calls using jQuery. The user enters in a country, presses the Search button, and the AJAX call is made to the API. The user then sees random facts displayed about the country they searched for.
My problem is that I want to allow the user to reset the form, and the facts automatically disappear. I got up to this point, but when I enter in a second country, the facts don't want to pop up anymore.
I should also mention that I'm using css.animate to animate a few elements on the page. I wonder if that might be messing things up. Can anyone help me out here? I would really like to put the finishing touches on this simple website.
Here's my HTML:
<h1 class = "animated infinte bounce"> World Facts </h1>
<div class = "info">
<p> Enter in a country to get some information about it! </p>
<form class = "zipform">
<input type ="text" class = "pure-input-rounded">
<button type = "submit" class = "pure_button"> Search </button>
<input type="reset" value="Reset">
</form>
<div class = "world_facts">
<p id = "region"> </p>
<p id = "capital"> </p>
<p id = "people"> </p>
<p id = "nat_name"> </p>
<p id = "domain"> </p>
</div>
</div>
And my JS/jQuery:
`$('.pure_button').click(function(e) {
e.preventDefault()
console.log("click noticed")
$.ajax({
url: //API URL HERE,
type: "GET",
success: function(data) {
var country = $('.pure-input-rounded').val();
console.log("This works too")
debugger
console.log(data)
var capital = data[0].capital
var people = data[0].demonym
var region = data[0].region
var nat_name = data[0].nativeName
var domain = data[0].topLevelDomain
$('.world_facts').addClass("animated fadeInDown")
$('#region').text(country + " is located in " + region + ".")
$('#capital').text("Its capital is " + capital + ".")
$('#people').text("People from " + country + " are called " + people + ".")
$('#nat_name').text(people + " people call their country " + nat_name + ".")
$('#domain').text("Websites registered in " + country + " have the top level domain name of " + domain + ".")
}
});
});
$(":reset").click(function(e) {
e.preventDefault()
$(".zipform")[0].reset()
console.log("Form reset")
$(".world_facts").text("")
});`
Because when you call
$(".world_facts").text("")
You are removing all the children elements so they no longer exist. You need to remove the text from the children.
$(".world_facts p").text("")
Don't use .text("") upon the div, since you lose all the elements within. Besides, you can use .empty().
So, change the line to: $(".world_facts p").empty();
Here's an example:
http://jsbin.com/didumiyexi/1/edit
By doing $(".world_facts").text("") you aren't removing text from all individual nodes inside that element but (as intended) you basically remove the entire content of what's inside that particular div
You can reset it in the following way instead:
$('.world_facts > p').text("");
This selector targets every immediate <p> inside the world_facts container and sets its text to blank
example:
$('.pure_button').click(function(e) {
e.preventDefault()
console.log("click noticed")
var data = [{
capital: 'London',
demonym: 'British',
region: 'Europe',
nativeName: 'UK',
topLevelDomain: 'co.uk'
}];
var country = $('.pure-input-rounded').val();
var capital = data[0].capital
var people = data[0].demonym
var region = data[0].region
var nat_name = data[0].nativeName
var domain = data[0].topLevelDomain
$('.world_facts').addClass("animated fadeInDown")
$('#region').text(country + " is located in " + region + ".")
$('#capital').text("Its capital is " + capital + ".")
$('#people').text("People from " + country + " are called " + people + ".")
$('#nat_name').text(people + " people call their country " + nat_name + ".")
$('#domain').text("Websites registered in " + country + " have the top level domain name of " + domain + ".")
});
$(":reset").click(function(e) {
e.preventDefault();
$(".zipform")[0].reset();
// instead, clear each form separately
$('.world_facts > p').text("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<h1 class="animated infinte bounce"> World Facts </h1>
<div class="info">
<p>Enter in a country to get some information about it!</p>
<form class="zipform">
<input type="text" class="pure-input-rounded">
<button type="submit" class="pure_button">Search</button>
<input type="reset" value="Reset">
</form>
<div class="world_facts">
<p id="region"></p>
<p id="capital"></p>
<p id="people"></p>
<p id="nat_name"></p>
<p id="domain"></p>
</div>
</div>
Related
On my form I am trying to have specific output fields and their strings output as Title Case. May be worth noting, this form outputs to results on the same page. Here's a Fiddle demo of my form.
As you can see from it I have 3 input categories Name, City and Words, for this example I am trying to implement the Title Case script to just the 'Name" and City" output strings without it effecting the "Words" category. As I don't want to convert an ongoing sentence to Title Case.
I found a lot of discussion here on how to convert to title case. However I am having difficulty implementing this in to my form as I am still new to JavaScript. All the examples show the script, but not how to implement it in a form.
I was playing around with Greg Dean's top answer to try and target the specific inputs like so...
toTitleCase = function(str)
{
var name = document.getElementById('name');
var city = document.getElementById('city');
return str.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
However this does not seem to be working.
Here's the HTMl:
<form>
<input type="text" class="text" id="name" placeholder="Name">
<br>
<input type="text" class="text" id="city" placeholder="City">
<br>
<textarea type="textarea" id="words" placeholder="Words" cols="70" rows="6">
</textarea>
<br>
<input type="button" value="Combine" onclick="convert()">
<br>
<div class="wrap"><span id="CharCountLabel1" class="counter"></span>
<textarea type="textarea" name="output" id="output" cols="70" rows="10"
maxlength='' placeholder="Output"></textarea>
</div>
<br>
<button type="reset" onclick="ResetForm();" value="Reset
form">Reset form</button>
</form>
And the rest of the script:
function convert() {
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
var words = document.getElementById("words").value;
//input = wordwrap(input, 70, true);
var output = "";
if(!document.getElementById("name").disabled){
output += "Name: " + name + "\n";
}
if(!document.getElementById("city").disabled){
output += "City: " + city + "\n";
}
if(!document.getElementById("words").disabled){
output += "The words are... " + words + "\n";
}
document.getElementById("output").value = output;
}
CharacterCount = function(output,FieldToCount){
var myField = document.getElementById(output);
var myLabel = document.getElementById(FieldToCount);
var Chars = myField.length;
if(!Chars){Chars = "" ; };
var remainingChars = Chars + myField.value.length
myLabel.innerHTML = remainingChars+""+Chars
}
setInterval(function(){CharacterCount('output','CharCountLabel1')},55);
How do I target the script to just the specified input fields? Please no jQuery, just JavaScript solutions.
While you have a fully-function toTitleCase() function, you're never actually calling it. All you need to do is run your name and city variables through your toTitleCase function when you go to output them to the page:
if (!document.getElementById("name").disabled) {
output += "Name: " + toTitleCase(name) + "\n";
}
if (!document.getElementById("city").disabled) {
output += "City: " + toTitleCase(city) + "\n";
}
To prevent the words from also being transformed, simply don't pass that variable to the function:
if (!document.getElementById("words").disabled) {
output += "The words are... " + words + "\n";
}
A working demo of this can be seen here.
Hope this helps! :)
I am starting to learn javascript and I have a small project work complete. I would like to take the information from a form and create an ics file for 3 single events - an original date, a 5 day event, a 20 day event. Below is the entire html and javascript code. This will be an internal file, it won't go online.
So far i've been able to create the form and an alert box that pulls the information presented. I would like to keep it scrictly javascript and not jQuery - as that is beyond my skill level and comprehension.
Thank you so much friends. .
<form>
<fieldset>
<legend>NUMC Information</legend>
Handler: <select>
<option value = "Ronald" >Ronald</option>
<option value = "Thomas">Thomas</option>
<option value = "Elizabeth">Elizabeth</option>
</select>
</fieldset>
</form>
<br>
<fieldset>
<legend>FOIL Contact</legend>
<form>
First name:<br>
<input type="text" id="firstname">
<br>
Last name:<br>
<input type="text" id="lastname">
<br>
Email:<br>
<input type="email" id="email">
<br>
Phone:<br>
<input type="text" id="phone">
</form>
</fieldset>
<br>
<div class="origin-event" >Origin Event">
<form id="eventForm">
<fieldset>
<legend>New FOIL Calendar Event</legend>
<legend>FOIL Origin Date</legend>
<fieldset>
<div>
Title: <input type="text" id="summary" >
<br><br>
Origin Date: <input type="date" id = "originDate"/>
<br>
</div>
</fieldset>
<br>
<legend>FOIL 5 Day Reminder</legend>
<fieldset>
<div>
5 Day Reminder Date: <input type="date" id = "5dayDate"/>
<br>
</div>
</fieldset>
<br>
<legend>FOIL 20 Day Reminder</legend>
<fieldset>
<div>
20 Day Reminder Date: <input type="date" id = "20dayDate"/>
<br>
</fieldset>
<br>
Description:
<br>
<textarea id="description" name="description"></textarea>
<br>
Location:
<br>
<input value="New York" id="location">
</div>
</fieldset>
</form>
</div>
<br>
<div class = "buttons">
</div>
<div class="wrap">
<button type="button" onclick="getValue()">Create Origin Date Noficiation</button></a>
<br>
</div>
<script>
function getValue()
{
var title= "Title: " + document.getElementById("summary").value;
var description = "Description: " + document.getElementById("description").value;
var location = "Location: " + document.getElementById("location").value;
var originalDate = "Origin Date: " + document.getElementById( "originDate").value;
var FiveDay = "Five Day: " + document.getElementById( "5dayDate").value;
var TwentyDay = "Twenty Day: " + document.getElementById( "20dayDate").value;
alert(title + "\n" + description + "\n" + location + "\n" + originalDate + "\n" + FiveDay + "\n" + TwentyDay);
}
</script>
I found a possible solution at https://github.com/nwcell/ics.js and https://github.com/matthiasanderer/icsFormatter but its just blowing my mind how to manipulate it to fit my needs.
Thoughts?
Thanks everyone for your help.
I have completely the project.
The sample page can be found here: https://dl.dropboxusercontent.com/u/25536938/FOIL%20Reminder.html
The code I came up with was:
<script>
// Demo
// access text property of selected option
var val = "Contact Name: " + sel.options[sel.selectedIndex].text;
function createEvent() {
var cal_single = ics();
var cal = ics();
var sel = document.forms['form'].elements['category'];
// value property of select list (from selected option)
var val = sel.value;
// access text property of selected option
var val = "Handler: " + sel.options[sel.selectedIndex].text;
var FiveDaysubject = document.getElementById("summary").value + " (Five Day Reminder)";
var TwentyDaysubject = document.getElementById("summary").value + " (Twenty Day Reminder)";
var foilFirst = " Contact First Name: " + document.getElementById("firstname").value;
var foilLast = " Contact Last Name: " + document.getElementById("lastname").value;
var foilEmail = " Contact Email: " + document.getElementById("email").value;
var foilPhone = " Contact Phone: " + document.getElementById("phone").value;
var originalDate = new Date(form.originDate.value);
originalDate.setDate(originalDate.getDate() + 1);
var FiveDayDate = new Date(form.FiveDay.value);
FiveDayDate.setDate(FiveDayDate.getDate() + 1);
var TwentyDayDate = new Date(form.TwentyDay.value);
TwentyDayDate.setDate(TwentyDayDate.getDate() + 1);
var description = val + foilFirst + foilLast + foilEmail + foilPhone + " Description: " + document.getElementById("description").value + " Origin Date: " + originalDate;
var location = "New York";
cal_single.addEvent(FiveDaysubject, description, '', FiveDayDate, FiveDayDate);
cal.addEvent(TwentyDaysubject, description, '', TwentyDayDate, TwentyDayDate);
cal_single.download(FiveDaysubject);
cal.download(TwentyDaysubject);
}
</script>
The original ics.js was a good initiative, but the original has some critical flaws.
There are several forks that solved at least major output problem: Time doesn't show up if minutes and seconds are 0, which looks like a duplicate of Lacking Minute Issue, both totally ignored by the original author.
Specifically, I liked this fork https://github.com/connorbode/ics.js based on having multiple contributors and some pull requests and merges in its history.
You cannot do this purely in Javascript. You'd need some help from the server to make a file.
But you could try using a library called Downloadify and see if that will do it for you!
Cheers!
i'm trying to populate div with select option but i don't really now where to start...
i have some code to live edit the "title" of the div, but now i want to add to a specific div his option...
Here's the code that i have for now:
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
$(".design-your-system-page-playground-container").show();
for (var i = 0; i < rooms; i++) {
// $("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
// $("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
//
$("<div class='design-your-system-page-rooms targetDiv_" + roomcounter + "'>Room-" + roomcounter + "</div>").appendTo(".design-your-system-page-house");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' class='textInput' lang='targetText_" + roomcounter + "'> <select>Heating<option value='radiator'>Radiator</option><option value='underfloor'>Underfloor</option><option value='electric'>Electric</option></select> <select class='design-your-system-number-of-radiator-select'><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><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option></select> <span>Do you want the room to be smart (footprint) ?<input type='radio' name='smart-yes' value='smart-yes'>Yes</input> <input type='radio' name='smart-no' value='smart-no'>No</input></div></br>").appendTo(".design-your-system-page-edit-room-container");
roomcounter++;
};
if ($('.design-your-system-page-house').find('.design-your-system-page-rooms').length) {
$("#buttonaddrooms").hide();
}
$("input.textInput").on("keyup", function () {
var target = $(this).attr("lang").replace("Text", "Div");
$("." + target).text($(this).val());
});
as you can see, when i click the button, i'll append to the parent as many child divs as the value typed into the textbox and i also create the same number of "row" containing the name and other option (two select and a radio)
i'm already able to live edit the name of the ralative div, but now i want to add to that div also the other options
here a jsfiddle to help you understand what i have and what i want:
http://jsfiddle.net/3cyST/
if is not clear please tell me.
thanks
please check this fiddle:
i made your target variable global to be reusable, i also added a class for your first select element which is selecting
ive updated it and it now appends the value of your test onchange using:
$("select.selecting").on("change", function () {
$("." + target).append($(this).val());
});
you can work for the rest now.
EDIT(for the question of OP on the comment) :
to get value of radio button i'll give you 2 ways :
in Javascript :
if (document.getElementById('ID_OF_RADIO').checked) {
rate_value = document.getElementById('ID_OF_RADIO').value;
}
in jQuery :
$("input[name=RADIO_NAME]:checked").val();
give the select an id, then use
$("#id").on("change",function(){
console.log(this.value);
//whatever you want to do with the value
})
...same for the radio buttons and other options...also note that the radio buttons shouldn't have different names:
<input type='radio' name='radio_{put id here}' value='yes'>Yes</input>
<input type='radio' name='radio_{put id here}' value='no'>No</input>
another thing for the readabillity of the code: try using a template....just put a <noscript> with an id in the code...use some distinctive syntax to put placeholders in it, and replace them at runtime:
HTML:
<noscript id="template">
RoomName: <input type="text" id="roomName_%ROOMID%" />
Do you want...
<input type='radio' name='radio_%ROOMID%' value='yes'>Yes</input>
<input type='radio' name='radio_%ROOMID%' value='no'>No</input>
</noscript>
JS:
for (var i = 0; i < rooms; i++) {
var tplcode = $("#template").html();
tplcode = tplcode.replaceAll("%ROOMID%",roomcounter);
$($.pareHTML(tplcode)).appendTo(".design-your-system-page-edit-room-container");
$("input[name='radio_"+roomcounter+"']").on("change",function(){
console.log("user wants:" + $("input[name='radio_"+roomcounter+"'][checked]").val())
});
roomcounter++;
}
// these functions help replacing multiple occurances
String.prototype.replaceAll = function(find,replace){
return this.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
//escapse all regEx chars, so the string may be used in a regEx
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Fiddle: http://jsfiddle.net/3cyST/4/
This question is in the continuation of another question I have asked earlier URL
I am generating rows dynamically and and all the fields are being populated using JS thus the input ID's for all text boxes are different. Now if a user enter some number on "Apply to all" input field and click the button the same number should be set to all the rows which are added in the betslip.
HTML structure where I am adding rows dynamically
<div id="bets">
<div id="idNo1" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_1" type="text">
</div>
</div>
<div id="idNo2" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_2" type="text">
</div>
</div>
<div id="idNo3" class="bet gray2" name="singleBet">
<div class="left">
<p class="title">
<p class="supermid">
<input id="input_3" type="text">
</div>
</div>
</div>
JS for adding element in the individual bets
BetSlip.prototype.createSingleBetDiv = function(Bet) {
var id = Bet.betType + '_' + Bet.productId + '_' + Bet.mpid,
divId = id + '_div';
// If such bet already exists
if (typeof document.betSlip.singleDivs[divId] == "undefined") {
var div = element.create('div'),
a = element.create('a'),
leftDiv = element.create('div'),
closeDiv = element.create('div'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
element.setId(div, divId);
element.setName(div, 'singleBet');
element.setClassName(div, 'bet gray2');
element.setClassName(a, 'right orange');
element.setClassName(leftDiv, 'left');
element.setClassName(closeDiv, 'icon_shut_bet');
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + Bet['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + Bet['betTypeName'] + ' (' + Bet['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {document.betSlip.removeSingleBet(divId);};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'Bet', Bet);
// Add div to the bet slip map
document.betSlip.singleDivs[divId] = div;
return div;
}
else {
$("#betSlipError").show();
$("#betSlipError").html(sameBet);
return null;
}
}
HTML for applyTOall button
<a onclick="document.betSlip.applyToAll(event)" class="button apply orange">APPLY TO ALL <input type="text"> </a>
JS for applyToall function
BetSlip.prototype.applyToAll = function(e) {
e.preventDefault();
document.betSlip.applyToAllBetInput($(this).find("input").val());
}
BetSlip.prototype.applyToAllBetInput = function(value) {
$("#bets div[name=singleBet] .supermid input:text").val(value);
}
Try doing this way:
$('yourbutton').on('click', function(){
var applyVal = $('applyvalinput').val();
$('#bets').find('[id^="input"][type="text"]').val(applyVal);
});//^------finds the inputs in this specific div.
Click your button and cache the value of your apply to all input val and check for the inputs which has the ids started [id^="input"] by the term input and it applies the value to each text input.
I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
What I want to do is to click only once to display the books.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>
Because the append script runs async, global variable error is undefined until you get the response from the server.
You should put your process block of code in the onload event of bt script element like this,
bt.onload = function () {
if(error==1)
{
// code
}
// more code
}
a working example can be found here :
http://jsfiddle.net/Rad3q/
You mean the user has to double click the button instead of 1 click?
<input type="button" value="Search (2 clicks)" ondblclick="ebook();">