Hi this is working when I include the code inside of my html but when I shift it out into myScript.js I get no results, can anyone point out where I've gone wrong with this as I'd like to be able to access this function across several pages?
I've also got the side issue that if I enter something, then delete the input value my filtered array shows all the options, is it possible to set this to a "" value if the input box contains no value?
Thanks
function page_search(){
var pages = [
{name: "Test",url: "Test.html"},
{name: "Rest",url: "Rest.html"},
{name: "Best",url: "Best.html"},
];
let input = document.getElementById('searchbar').value
input=input.toLowerCase();
let x = document.getElementById('searchresults');
var results = [];
for(var i=0;i<pages.length;i++){
if(pages[i].name.toLowerCase().indexOf(input) > -1)
results.push("<a href='"+pages[i].url+"' target='_blank'>"+pages[i].name+"</a>")
}
if(results.length == 0)
$(x).html("No Results Found");
else
$(x).html(results.join("<br>"));
return results;
}
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
<div class="searchbar">
<input type="text" id="searchbar" onkeyup="page_search()" placeholder="" value="Search.." maxlenght="25" autocomplete="off"/>
</div>
<div id="searchresults"></div>
</body>
</html>
I have added the code, it will definitely resolve your second issue of displaying "" when input box is empty. I am not able to replicate your first issue, can you please tell what is error you are getting ?
function page_search() {
var pages = [{
name: "Test",
url: "Test.html"
},
{
name: "Rest",
url: "Rest.html"
},
{
name: "Best",
url: "Best.html"
},
];
let input = $('#searchbar').val().toLowerCase()
let x = $('#searchresults');
var results = [];
if (input) {
for (var i = 0; i < pages.length; i++) {
if (pages[i].name.toLowerCase().indexOf(input) > -1) {
results.push(`${pages[i].name}`);
}
}
} else {
$(x).html("");
return;
}
if (results.length == 0)
$(x).html("No Results Found");
else
$(x).html(results.join("<br>"));
}
var ele = document.getElementById('searchbar');
ele.addEventListener('keyup', page_search);
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="searchbarC">
<input type="text" id="searchbar" placeholder="Search.." maxlenght="25" />
</div>
<div id="searchresults"></div>
<script src="myScript.js" type="text/javascript"></script>
</body>
</html>
Related
I am using Mustache to generate pages based on Data.
My problem: I need to getElementbyid in the page generated by Mustache. However, it always returns NULL. Do you have any ideas how I can fix it ? (I left a comment in main.js in the part where I am having issues.)
3 pages to reproduce my case:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="test-id">
<!-- Generated Content -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
template_page.html (where Mustache generate a page based on Data)
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="template-div">
<!-- part filled by Mustache -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
<script src="mustache.js"></script>
<script src="../node_modules/file-system/file-system.js"></script>
</body>
</html>
And the javascript part
main.js
document.addEventListener('DOMContentLoaded', function() {
// I get NULL but I want to find a way to get a None null value !!!
console.log(document.getElementById("test-get-id-value"));
// Data to get the different pages
var ALL_DATA = [
{
'lastname': 'lastname_1',
'firstname': 'firstname_1'
},
{
'lastname': 'lastname_2',
'firstname': 'firstname_2'
},
{
'lastname': '"lastname_3"',
'firstname': 'firstname_3'
}
];
// Function to get the different links
function displayData(obj_name) {
var theDiv = document.getElementById("test-id");
obj_name.forEach(doc => {
var lastname = doc['lastname'];
var firstname = doc['firstname'];
newdiv = document.createElement("div")
var text = document.createTextNode(lastname + ' ' + firstname);
var anchor_value = document.createElement("a")
url = lastname + firstname + '.html'
anchor_value.setAttribute("href", "template_page.html" + "?firstname=" + firstname + "&lastname=" + lastname);
anchor_value.setAttribute("class", "link-a");
anchor_value.onclick = createPage();
anchor_value.appendChild(document.createTextNode("Contact him"));
newdiv.appendChild(text);
newdiv.appendChild(anchor_value);
theDiv.appendChild(newdiv);
});
};
displayData(ALL_DATA);
// Function to create the PAGE based on the Data
function createPage() {
// get url parameters
var url = new URL(window.location.href);
var firstname_value = url.searchParams.get("firstname");
var lastname_value = url.searchParams.get("lastname");
// get the data needed
data = {
'lastname': lastname_value,
'firstname': firstname_value
};
var template =
`
<h1> Welcome, {{firstname}} </h1>
<h2> Your last name: {{lastname}} </h2>
<form id="test-get-id-value">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
`
var html = Mustache.render(template, data);
$("#template-div").html(html);
};
});
Your listener for DOMContentLoaded fires when you first load your page, and at that instant, no html has been rendered by Mustache
You can get the non-null value only after the template is rendered, so execute all your logic after render of the template:
var html = Mustache.render(template, data);
$("#template-div").html(html);
var el = document.getElementById("test-get-id-value");
// Now run the logic you need
I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one
I'm working on a tournament bracketing system, and I found a library called "JQuery bracket" which can help a lot. But there are some problems:
I was planning to retrieve team names (and possibly match scores) from a PostgreSQL database and put them on the brackets. However, the data must be in JSON, and the parser is in Javascript. I can't seem to figure out a workaround.
Original code:
<html>
<head>
<title>jQuery Bracket editor</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="jquery.bracket.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.bracket.min.css" />
<style type="text/css">
.empty {
background-color: #FCC;
}
.invalid {
background-color: #FC6;
}
</style>
<script type="text/javascript">
function newFields() {
return 'Bracket name [a-z0-9_] <input type="text" id="bracketId" class="empty" /><input type="submit" value="Create" disabled />'
}
function newBracket() {
$('#editor').empty().bracket({
save: function(data){
$('pre').text(jQuery.toJSON(data))
}
})
$('#fields').html(newFields())
}
function refreshSelect(pick) {
var select = $('#bracketSelect').empty()
$('<option value="">New bracket</option>').appendTo(select)
$.getJSON('rest.php?op=list', function(data) {
$.each(data, function(i, e) {
select.append('<option value="'+e+'">'+e+'</option>')
})
}).success(function() {
if (pick) {
select.find(':selected').removeAttr('seleceted')
select.find('option[value="'+pick+'"]').attr('selected','selected')
select.change()
}
})
}
function hash() {
var bracket = null
var parts = window.location.href.replace(/#!([a-z0-9_]+)$/gi, function(m, match) {
bracket = match
});
return bracket;
}
$(document).ready(newBracket)
$(document).ready(function() {
newBracket()
$('input#bracketId').live('keyup', function() {
var input = $(this)
var submit = $('input[value="Create"]')
if (input.val().length === 0) {
input.removeClass('invalid')
input.addClass('empty')
submit.attr('disabled', 'disabled')
}
else if (input.val().match(/[^0-9a-z_]+/)) {
input.addClass('invalid')
submit.attr('disabled', 'disabled')
}
else {
input.removeClass('empty invalid')
submit.removeAttr('disabled')
}
})
$('input[value="Create"]').live('click', function() {
$(this).attr('disabled', 'disabled')
var input = $('input#bracketId')
var bracketId = input.val()
if (bracketId.match(/[^0-9a-z_]+/))
return
var data = $('#editor').bracket('data')
var json = jQuery.toJSON(data)
$.getJSON('rest.php?op=set&id='+bracketId+'&data='+json)
.success(function() {
refreshSelect(bracketId)
})
})
refreshSelect(hash())
$('#bracketSelect').change(function() {
var value = $(this).val()
location.hash = '#!'+value
if (!value) {
newBracket()
return
}
$('#fields').empty()
$.getJSON('rest.php?op=get&id='+value, function(data) {
$('#editor').empty().bracket({
init: data,
save: function(data){
var json = jQuery.toJSON(data)
$('pre').text(jQuery.toJSON(data))
$.getJSON('rest.php?op=set&id='+value+'&data='+json)
}
})
}).error(function() { })
})
})
</script>
</head>
<body>
Pick bracket: <select id="bracketSelect"></select>
<div id="main">
<h1>jQuery Bracket editor</h1>
<div id="editor"></div>
<div style="clear: both;" id="fields"></div>
<pre></pre>
</div>
</body>
</html>
After the data is retrieved, upon display, you are going to want to add disabled to the html input element. For instance:
<input type="text" id="bracketId" class="empty" disabled>
This will render your text field uneditable.
If you are looking to do this as people are filling out their brackets, I would suggest you either add a <button> after each bracket or fire a jquery event with the mouseout() listener that adds the disabled attribute to your input fields.
I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')
Why doesn't this code work? I want it to change the color of the input background whether the value is correct (green) or not (red).
<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
if(username == document.getElementById('keygen').value ) {
document.getElementById('keygen').style.backgroundColor = '#5bc556';
}
else {
colorchange.style.backgroundColor = 'red';
}
}
return 0;
</script>
</head>
<body>
<input type="text" id="keygen">
<button onclick="funct1"></button>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
var keygen = document.getElementById('keygen');
if(username == keygen.value) {
keygen.style.backgroundColor = '#5bc556';
} else {
keygen.style.backgroundColor = 'red';
}
}
</script>
</head>
<body>
<input type="text" id="keygen" />
<button onclick="funct1()">Button Title</button>
</body>
</html>
The above should help. Also, you may want to look into this:
Give more descriptive names to functions you declare.
Save time by eliminating calls to "getElementById" by storing DOM elements in variables.