How can I go about calling this function through a dropdown menu and the for loop catching all data and not just the last? I've tried some things and all I would get is the last bit of information. Thank you in advance.
<script>
function hey(){
for (i = 1; i < radio.length; i++){
document.write('<div class="dell"><img class="dell3" align="left" src=images/' + radio[i].image + '> <div class="space"> <font size="4">' + i + '. ' + radio[i].name + '</font></br><font color="silver">' + radio[i].category + '</br>' + radio[i].address + '</br>' + radio[i].citystate + '</font></div> </div>');
}
}
</script>
Add class to every item of <select>(<option>).
Get nodelist of option-elements:
const optionList = document.querySelectorAll('.class');
And for each element add event listener with desired function:
optionList.forEach(item => item.addEventListener('event', fucntion(){}));
Edit your code a bit because it's confusing to scroll.
Related
I am creating a search engine of sorts, using the Wikipedia API to query content. As it currently stands, the user can make a search input and the page returns the top 10 results with links and snippets. I run into difficulty when the user makes another search, in which case the page simply appends the original search results again. I have tried using replaceWith() and html(), but they either prevent the search results from coming through at all (if I put them within the event handler), or they don't get triggered (if they are outside the event handler). I am hoping to achieve a result where the user can make another input and the page will replace the current content with the new search results.
Here is what I have currently:
JS:
var results = [];
$("#search").on("keydown", "#searchinput", function(event) {
if (event.key === "Enter") {
var searchParameter = encodeURIComponent(this.value);
var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";
$.getJSON(link, function(data) {
for (var key in data) {
results.push(data[key]);
}
for (var i = 0; i < 10; i++) {
$("#results").append("<div class=\"resultContent\">" + "<h2>" + "" + results[1][i] + "" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
}
})
}
})
HTML:
Feeling Bold? Click Here for a Random Article
<div id="search">
<span>Search:</span>
<input type="text" id="searchinput" autocomplete="off"></input>
</div>
<div id="results"></div>
Thanks for the help!
You can remove the current results just before your loop:
$("#results").empty();
for (var i = 0; i < 10; i++) {
$("#results").append("<div class=\"resultContent\">" + "<h2>" + "" + results[1][i] + "" + "</h2>" + "<p>" + results[2][i] + "<br/>" + "</p>")
}
THIS QUESTION IS SOLVED VIA COMMENTS. WORKING SOLUTION IS POSTED BELOW
So I got this piece of code that I am trying to adapt as it ain't showing the way I wish.
function writeRow(row) {
var spans = '';
for (var i = 0; i < num_of_fields; ++i) {
// to do: append for select type field -> if select write: name, value, title
// to do: add class "debug" to name, and for select tag value
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
}
spans += ' ×';
$('#outer-list').append($('<li id="row_' + row_id++ +'">').append(spans));
}
The issue is with this line:
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
The problem is that when the row[field[i].name] inside the .value <span> is empty it still shows the name and a empty value field.
So I thought to replace that line with a if/else like if .value <span> is empty then //do nothing else CODE FROM ABOVE.
As I am not going to ask a question without trying to fix it by myself first here are the attempts I made so far, please keep in mind that I placed all these if else at the same place as the single line of code above!
Attempt 1
if $(row[field[i].name]).length == 0) {
// Do nothing
} else {
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
}
Attempt 2
if $(row[field[i].name]).val().trim().length == 0) {
// Do nothing
} else {
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
}
The attempts are not in the right order but those 2 where left in the document as comments I tried a couple of other things as well including :empty but I already deleted them from the comments section.
Thanks in advance for any help. And if something is not clear please let me know.
Attempt 3 with help from Mike C
var row_id = 0; // row counter
function writeRow(row) {
var spans = '';
for (var i = 0; i < num_of_fields; ++i) {
// to do: append for select type field -> if select write: name, value, title
// to do: add class "debug" to name, and for select tag value
if row[field[i].name].length == 0) {
// Do nothing
} else {
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
}
}
spans += ' ×';
$('#outer-list').append($('<li id="row_' + row_id++ +'">').append(spans));
}
I am answering it myself as I don't want to have too many questions with no answers as it could get me blocked! Can't have that. Too be clear this answers credits should go to MikeC. But he never posted the answer as answer but as comment. I asked him together with some others to please post a answer so we could accept it. He never did so therefore I post his answer myself.
Working solution by Mike C
var row_id = 0; // row counter
function writeRow(row) {
var spans = '';
for (var i = 0; i < num_of_fields; ++i) {
// to do: append for select type field -> if select write: name, value, title
// to do: add class "debug" to name, and for select tag value
if (row[field[i].name].length == 0) {
// Do nothing
} else {
spans += '<div><span class="name"><b>' + field[i].name + ':</b></span> <span class="value">' + row[field[i].name] + '</span></div> ';
}
}
spans += ' ×';
$('#outer-list').append($('<li id="row_' + row_id++ +'">').append(spans));
}
strange situation happening here. I'm using the jquery plugin chosen.js. I'm updating a dropdown that is already on the page with an ajax call and jquery. here is a little bit of the sample code.
here is my dropdown as shown in the page.
<div id="singleDropDownBlock" style="display: none">
<select id="SingleDropDown" class="chzn-select" data-placeholder="Choose your start Location" onchange="GetFromNodeValue();">
<!--<option>select a strating locnation based on category.</option>-->
</select>
</div>
This is the code loading the values into the dropdown using jquery.
function GetResultsFromMultiCategory(data)
{
for (i = 0; i < data.d.categories.length; i++)
{
//console.log(data.d.categories[i].catNode);
if (data.d.categories[i].catNode == "0")
{
$('#SingleDropDown').append("<optgroup " + "label= " + '"' + data.d.categories[i].catName + '"' + ">");
console.log("<optgroup " + "label= " + '"' + data.d.categories[i].catName + '"' + ">");
//onOrOff = false; </optgroup>
}
else
{
$('#SingleDropDown').append("<option " + "value=" + data.d.categories[i].catNode+ ">" + data.d.categories[i].catLoc + "</option>");
console.log("<option " + "value='" + data.d.categories[i].catNode + "'>" + data.d.categories[i].catLoc + "</option>");
if (typeof(data.d.categories[i + 1]) != "undefined")
{
if (data.d.categories[i + 1].catNode == "0")
{
$('#SingleDropDown').append("</optgroup>");
console.log("</optgroup>");
}//end second if
}//end first if
}//end else
}
$('#SingleDropDown').append("</optgroup>");
console.log("</optgroup>");
$("#SingleDropDown").chosen({ placeholder_text_single: "Choose Map" });
$("#SingleDropDown").trigger("chosen:updated");
}
for some reason chosen does not update with the it only updates with the . Is there anything I'm missing? can someone please point me in the right direction.
I also can't get chosen to update the placeholder. All i get is the first item in list as the display.
thanks in advance for any help you can offer.
I have finally figured out my issue. I'll post the answer here so that it may help someone else someday.
The problem here is that appending one select at a time was being closed by the browser. Therefore here is the best way to do this.
function GetResultsFromMultiCategory(data)
{
$("#singleDropDownBlock").show();
$('#SingleDropDown').append("<option></option>");
var myOptions = '';
for (i = 0; i < data.d.categories.length; i++)
{
if (data.d.categories[i].catNode == "0")
{
myOptions += "<optgroup " + "label= " + '"' + data.d.categories[i].catName + '"' + ">";
}
else
{
myOptions += "<option " + "value=" + data.d.categories[i].catNode + ">" + data.d.categories[i].catLoc + "</option>";
if (typeof(data.d.categories[i + 1]) != "undefined")
{
if (data.d.categories[i + 1].catNode == "0")
{
myOptions += "</optgroup>";
}
}
}
}
myOptions += "</optgroup>";
$('#SingleDropDown').append(myOptions);
$("#SingleDropDown").chosen({placeholder_text_single: "Choose Start Location" });
}
the take away here is that when using append instead of appending each line, build the string and then append it to the html element.
Been a while since I last did JavaScript, but school forced us into a JavaScript project. So here I am, making a simple quiz game. Coming along quite nicely, yet I'm experiencing issues with probably something terribly simple.
var useranswers = new Array();
var imgArray = new Array();
var answered = 0;
var currentQuestion = 0;
function renderQuizViaArray()
{
document.writeln('<h1>' + questions[currentQuestion] + '</h1>');
for(i=0; i < choices[currentQuestion].length; i++)
{
document.writeln('<input type="radio" name="answer_' + currentQuestion + '" value="1" id="answer_' + currentQuestion + '_' + i + '" class="question_' + currentQuestion + '" onclick="submitAnswer(' + currentQuestion + ', this, \'question_' + currentQuestion + '\', \'label_' + currentQuestion + '_' + i + '\')" /><label id="label_' + currentQuestion + '_' + i + '" for="answer_' + currentQuestion + '_' + i + '"> ' + choices[currentQuestion][i] + '</label><br />');
}
document.write('<input type="submit" value="NEXT" onclick="nextQuestion()" />');
}
function nextQuestion()
{
currentQuestion++;
renderQuizViaArray();
}
Whenever I click the "NEXT" button, it loads the second question (Element[1]) from an Array as well as the answers of another Array onto the screen. But the page remains in an infinite loading state and Firebug gives the message: "Reload to activate window console"
Anyone?
I have probably found the issue, but no idea how to fix it.
As soon as I click the "NEXT" button, it executes the function renderQuizViaArray();. That's where it's completely messing up.. am I missing something?
What I basically want is, that the current displayed text gets updated with data of the next question including the answers.
These are the files it contains:
quiz.html: http://rapidimg.org/server/files/50ab9c326115cKAUf6S.png ........ quiz_questions.js: http://rapidimg.org/server/files/50ab9c536ed44UWhV54.png ......... quiz_functions.js: Shown in main post
don't use
for(i=0; i < choices[currentQuestion].length; i++)
use
for(i=0, j=choices[currentQuestion].length; i < j; i++)
function drawLabel(labelsIndex) {
// Check not deleted Label data:(DBID, text, styling, x, y, isDeleted)
if (!labelData[labelsIndex][5]) {
// Create
var newLabel = $('<div id="label' + labelsIndex + '" style="font-size:' + (labelData[labelsIndex][6] * currentScale) + 'px;z-index:9999;position:absolute;left:' + labelData[labelsIndex][3] + 'px;top:' + labelData[labelsIndex][4] + 'px;' + labelData[labelsIndex][2] + '">' + labelData[labelsIndex][1] + '</div>');
$('#thePage').append(newLabel);
// Click edit
$('#label' + labelsIndex).dblclick(function() {
if (!isDraggingMedia) {
var labelText = $('#label' + labelsIndex).html();
$('#label' + labelsIndex).html('<input type="text" id="labelTxtBox' + labelsIndex + '" value="' + labelText + '" />');
document.getElementById('#label' + labelsIndex).blur = (function(index) {
return function() {
var labelText = $('#labelTxtBox' + index).val();
$('#label' + index).html(labelText);
};
})(labelsIndex);
}
});
The code is meant to replace a div's text with a textbox, then when focus is lost, the textbox dissapears and the divs html becomes the textbox value.
Uncaught TypeError: Cannot set property 'blur' of null
$.draggable.start.isDraggingMediaresources.js:27
c.event.handlejquery1.4.4.js:63
I think I'm getting a tad confused with the scope, if anyone could give me some points I'd appreciate it. It would also be good if someone could show me how to remove the blur function after it has been executed (unbind?)
document.getElementById('#label' + labelsIndex).blur is a javascript function and less jquery :) therefore the # hash there is just irrelevant.
$('#label'+labelsIndex).bind('blur',function (){
//labelText value goes here //
});
EDIT
to be honest ur over complicating it :)
<div id="txt1">I am div</div>
<textarea id="txt2">I am text</textarea>
$('#edit_button').click(function (){
var val = $('#txt1').hide().html();// hide the div,then get value,
$('#txt2').show().val(val);//show txtarea then put value of div into it
});
Do the opposite for $('#save_button');