Using JS to read from a JSON file when button is clicked - javascript

I'm trying to solve a problem where a user inputs values into a search box, presses the search button and with the onClick event the search terms are compared to values in a JSON file. Currently I don't know jQuery so if this can be avoided in the solution I would appreciate it! What I have so far is:
<div id="searchb">
<button onclick="userSearch()">Search</button>
</div>
This is a simple div for the search button which calls the userSearch function that deals with the JSON file:
<script>
<!--Function which compares inputted name to names in the .json file. -->
function userSearch(thearr) {
... <!-- All of the code that compares the values -->
console.log();
}
</script>
<script src="filepath on my machine">
</script> <!-- Source path to .json file for script -->
The issue that I'm having is that the function in the onClick event doesn't pass any parameters, because the parameter for userSearch is not defined until the script tag is reached. When I run this 'applet' I get an error saying that the parameter thearr is undefined.
The file path is correct because I used it for a similar problem which automatically generated results from the JSON file on page load, it's the button click that seems to be the problem. Any ideas on how this issue could be fixed would be greatly appreciated! Thanks.
EDIT: Search box HTML as requested
<div id="textboxes">
<textarea id="input1" placeholder="First Name" rows="1" cols="10">
</textarea>
<textarea id="input2" placeholder="Surname" rows="1" cols="10"></textarea>
</div>

From your question, it sounds like you need to get the values from the users input. For userSearch(thearr), i'm not sure what you expect thearr to be. You can get the value of the user input like this:
function userSearch() {
var firstName = document.getElementById("input1").value;
var surName = document.getElementById("input2").value;
console.log(firstName + " " + surName);
}
Note: if you are expecting to process multiple first/surnames, you should rethink the architecture. The logic to do so with the current set up would not be simple to write and more importantly unnecessary.

Related

How to submit an HTML table's code from a textarea field then parse it into an array

I am trying to make a spreadsheet addon where I have a textarea field where users will be putting the HTML for a table in a field, and I need my script to then take that HTML code, parse it and convert it into an array or object by which I can easily access the table's cells.
The problem I'm facing is that I don't seem to be able to turn the HTML code submitted as text back into a jQuery object I can loop through.
Tl;Dr:
How do I submit a table's HTML code from a form as text and turn it back into an HTML object so I can turn the table into an array/object?
I'm using $("#invoice-info").val() to get its content but using any other methods afterwards gives errors (All of them are either nonspecific or something about "Expected expression but got >", sorry I'm new to JavaScript so I have a hard time debugging it).
Here's the relevant HTML for the form itself:
<form onsubmit="return(false)">
<div class="block col-contain">
<div>
<textarea class="width-100" id="invoice-info" rows="10"></textarea>
<label for="invoice-info">Invoice Table</label>
</div>
</div>
<div class="block" id="button-bar">
<button class="blue" id="make-receipt" onclick='doTest()'>Generate</button>
</div>
</form>
You need to take the result of $("#invoice-info").val() and put it in a domNode. Because it returns a string. var tempDomNode = document.createElement('div'); tempDomNode.innerHTML =$("#invoice-info").val().
So you 'convert' the string into a domNode and then you will be able to use that domNode with or without jQuery to construct your array.
Note : you have to handle the case of a malformed sting (not valid as HTML)
Edit : just found this question on SO : https://stackoverflow.com/a/11047751/1836175 seems to address the same problem.

Script is not running when added dynamically

{include file="head.tpl" title="Combate"}
{include file="navBar.tpl" dir=$dir}
<table id="CombatLister">
</table>
Nombre: <input type="text" id="nombrePJ">
AC <input type="number" id="ACPJ">
Iniciativa <input type="number" id="Init">
<button id="añadirParty" onclick="addPJButt()">Añadir</button>
<script>
function addPJButt(){
var name=document.getElementById("nombrePJ").value;
var ac=document.getElementById("ACPJ").value;
var iniciativa=parseInt(document.getElementById("Init").value);
addPJ(name,ac,iniciativa);
}
function addPJ(nombre,ac,init){
var table=document.getElementById("CombatLister");
var row=table.insertRow(0);
var cellNombre=row.insertCell(0);
var cellInit=row.insertCell(1);
var cellAc=row.insertCell(2);
cellNombre.innerHTML=nombre;
cellInit.innerHtml=init;
cellAc.innerHtml=ac;
}
</script>
<script>
{$x=0}
{foreach $party as $pj}
addPJ({$pj.nombre},{$pj.ac},{$pj.init})
{/foreach}
</script>
I have a smarty template that using an array from another page, adds it to the "CombatLister" table. however, for some reason, the addPJ() Script does not run. Im just learning the ropes of Javascript, so maybe im skipping something, but so far, i've got no answers on why it does not work.
I tried to check if the addPJ() script was wrong, using the addPJButt(), but the script is working: When i put data on the input types up there, they add the name correctly.
I dont think its a problem of Smarty. checking the source code of the page its similar, writting this where i call $pj:
<script>
addPJ(Galahad,14,5);
</script>
PS: As an extra problem, but not so important, on the insertCell methods of addPJ only the first cell is added.
addPJ(Galahad,14,5); is looking for an undefined variable Galahad.
you need to quote it so it gets printed as javascript string
Try
addPJ('{$pj.nombre}',{$pj.ac},{$pj.init})
Note: I haven't worked with smarty in years and assume the quotes will be literals

Script to pick up the HTML value of a page? Explanation inside

I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.
I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.

auto update the html dom for all the users whenever there's change

I am sorry for asking such a noob question. But I saw a video very long time ago and I think it was a framework based on jquery, where if a user makes some CRUD changes to an object, the object's properties are auto updated not only for 1 user, but on all the other users browser. I am trying to find it but I am all lost! I would really really appreciate if you could help me out. Thank you!
Lets say you have a html form that looks like this
<form>
<input type="text" name="firstName" value="Jackson" />
<input type="text" name="lastName" value="Rivera" />
<textarea name="lifestory">
When i was 2yo, spot died...
</textarea>
</form>
simply add an OnChange event on every element you want to dynamicly change:
<form>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<input .. .. onchange="shareValueWithOthers(this.name, this.value)"/>
<textarea onchange="shareValueWithOthers(this.name, this.innerHTML)">
When i was 2yo, spot died...
</textarea>
</form>
Notice that a change of the elements value (or in the case of the textarea - it's contents) causes the function shareValueWithOthers(this.name, this.value) starts to run. this.name is the variable for the name, this.value is the variable for the value, this.innerHTML is the variable for the contents.
Now you have to write a Javascript function so you can send the changes to the server. Look into AJAX. Make a function that sends a POST request to your PHP script.
Your PHP script should save all the values either in a database, or in JSON-format in a file on the server. JSON is the easiest. Look into JSON PHP PARSER.
Last but not least. If you do the right thing, and make sure that every new value that a user enters gets updated in your json file by your PHP script. You can make the last step. which is to make a javascript function that retrieves the JSON file. JSON stand for JavaScript Object Notation, so your javascript can use this right away.
What you will do next, is to change all the values in your DOM that look different from the values in your retrieved JSON object.
two type of protocol, Websocket or WebRTC.
socket.io is Websocket very popular and easy.
gevent-socketio for python
Plenty base on node.js. sailsjs, deployd, meteor

Why do two forms appear?

I am using jQuery and bootstrap to give drop-down search suggestions.Following is the html code.But when I type something in the search form and then clear the form.Two forms apears as in the picture.Why? I am new to jQuery. Thanks for any help.
<div class="container">
<div class="row">
<div class="span6 offset3">
<form class="form-search">
<input type="text" id="month" name="month" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
<div id="suggestions">
</div>
</form>
</div>
</div>
</div>
<script>
jQuery("#month").keyup(function(){
ajax('search', ['month'], 'suggestions')});
</script>
EDIT:
I am using web2py framwork.This is the search function's code:
def search():
if not request.vars.month: return dict()
month_start = request.vars.month
selected=complete('piracyfinder',month_start) #this line get the search results
return DIV(*[DIV(k['title'],
_onclick="jQuery('#month').val('%s')" % k['title'],
_onmouseover="this.style.backgroundColor='lightblue'",
_onmouseout="this.style.backgroundColor='white'"
) for k in selected])
It appears you are using the same function (i.e., search()) to fill in the suggestions as well as to create the form (though that function doesn't process the form when submitted). According to the logic, when request.vars.month is either empty or does not exist, the function returns an empty dict. This will result in the associated view (i.e., /views/[controller name]/search.html) being executed and returned. Presumably the search.html view contains the HTML code shown above. So, when you clear the input box, the keyup handler is triggered and sends an empty month variable, which results in a new copy of the form being sent back and inserted in the "suggestions" div. You can avoid this problem by checking whether request.vars.month exists:
if not request.vars.month:
return '' if 'month' in request.vars else dict()
A better approach might simply be to use different functions for the search form and the suggestions given that they do completely different things and don't share any code.
if not request.vars.month also applies to the month var existing but being empty. Therefore, it's returning the form.
You need to do one of these:
Have your "suggestions" code be in a different page/file
Add a isAJAX variable to the request (or some other way to identify AJAX requests)
Check if the variable exists, rather than checking if it is falsy.

Categories