Firing a function on click - javascript

I have addBanner() function shown below which is invoked every time I click addBanner button. This adds a input field and fires the ausu auto-suggestion jQuery script.
When I click addBanner() Button I get a input field and auto-suggestion works fine. Suppose I click addBanner() button again it adds another empty Input Field and auto-suggestion works fine for that too as the auto-suggest function is fired every time I click addBanner Function. But, if I want to edit the first Input Field which I had added there's conflict. Please tell me how to get the control back to the first input field.
var bnrc = 1;
var bnrl = 5;
function addBanner(divName){
if (bnrc == bnrl) {
alert("You have reached the limit of adding " + bnrc + " Banner companies.");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "banner_sugg";
newdiv.innerHTML = (bnrc + 1) + ". <input type='text' value='' name='banner[]' id='banner" + (bnrc + 1) + "' autocomplete='off' /> <input type='hidden' value='' name='bannerID[]' id='bannerID" + (bnrc + 1) + "' autocomplete='off' />";
document.getElementById(divName).appendChild(newdiv);
bnrc++;
}
$.fn.autosugguest({
className: 'banner_sugg',
methodType: 'POST',
minChars: 1,
rtnIDs: true,
dataFile: 'e_data.php'
});
}

Did you spell suggest wrong on purpose? I'm spelling it correctly below so you may need to alter it.
You are currently (re)calling $.fn.autosuggest({}) every time you add a new item, which may be breaking the previous items.
Try:
$(newDiv).autosuggest({})
So it only adds autosuggest functionality to the new div. And you should move the code above into the section where you create the newDiv as it's even being called on error.

Related

How to change the label of a checkbox in JavaScript?

Note: Willing to use jQuery, whatever is easier.
I have a form which when submitted, creates a checkbox input. The text of the checkbox should be equal to that of another text input when the form is submitted.
The checkbox is created as expected when I submit the form but it is blank and doesn't contain the text from the corresponding text area.
For a checkbox i'm not sure if I should be using .text, .innerhtml, .val etc and the previous questions I saw on here seemed unnecessarily complicated.
HTML:
<div id="listContainer">
<form id="listForm">
<input type="submit" value="Add">
<input id="listInput" class="textarea" placeholder="Add your list item here, then click submit.">
<div id="checkboxContainer">
</div>
</form>
</div>
JS:
//ADD LIST ITEM
$("#listForm").submit(function(ev) {
ev.preventDefault();
if ($("#listInput").val() == "") {
alert("Please enter the item name, then click 'Add'.");
} else {
listCount++;
var input = $("#listInput").val();
console.log("List Count: " + listCount);
console.log(input);
var cb = document.createElement('input');
cb.id = 'input' + listCount;
cb.type = 'checkbox';
document.getElementById("checkboxContainer").appendChild(cb);
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
//Store the list count
localStorage.setItem("listCount", listCount);
//Store the list title
localStorage.setItem("input" + listCount, input); //"Note " + noteCount + ": " +
this.submit();
}
});
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
These four lines can be cleaned up and fixed. The issue here is quite simple, however your constant back-and-forth between jQuery and plain JS makes things very difficult to read. I would suggest writing DOM manipulation in one or the other, but never both.
The error here is on the third line, which uses the selector $("label" + listCount). This selector will look for this element on the page, however you've only created the element - you haven't added it to the page yet.
Let's correct this and rewrite it in jQuery:
$("<label />") //create new label
.attr("id", "label" + listCount) //set ID
.attr("for", "input" + listCount) //set For
.html(input) //set contents
.appendTo("#checkboxContainer"); //add to checkbox container
Consider using the example above to rewrite your checkbox creation as well, that way you can avoid the mixture of jQuery/plain JS.

How to bring Radio Buttons inside an html link using Javascript

I’m looking for some help bringing Radio buttons that we have on a page inside a link. At the moment we have a Quiz with various questions with 4 possible choices for the respondent to choose. The text links work fine and advance the user to the next page, but the radio buttons don’t work. They are clickable, but they don’t advance you to the next page.
How would I bring the Radio buttons inside the link? I want the Radio buttons to send you forward, just like the text links.
Here is the test page for the Quiz (need to press Start Quiz to see the Radio buttons):
http://stephanieshipper.com/test/
Here is the piece of code from the .js file:
function updates(questions) {
for (i = 0; i < 20; i++) {
$("body").append("<article><p>" + questions[i] + "</p><input id='question-" + (i*10) + "-1' type='radio' order='1' name='question-" + i + "-0'><label for='question-" + (i*10) + "-1'>exactly like me</label><br><input id='question-" + (i*100) + "-2' type='radio' order='2' name='question-" + i + "-0'><label for='question-" + (i*100) + "-2'>sort of like me</label><br><input id='question-" + (i*1000) + "-3' type='radio' order='3' name='question-" + i + "-0'><label for='question-" + (i*1000) + "-3'>not really like me</label><br><input id='question-" + (i*10000) + "-4' type='radio' order='4' name='question-" + i + "-0'><label for='question-" + (i*1000) + "-4'>not at all like me</label><br></article>");
}
motions();
}
function motions() {
var step = 1;
results = [];
var order;
$("body > article > label").on("click", function() {
$(this).parent().hide(250);
if (step < 20) {
$(this).parent().next().show(250);
order = parseInt($(this).prev().attr("order"));
results[step-1] = order;
step++;
} else {
As I see, your are calling the next page just if the user click on the label tag :
$("body > article > label").on("click", function() {}
What you gonna need to do it's adding the radio button(your input tag), into this jquery
eg.:
$("input[type='radio']")
So maybe would work :
$("body > article >input[type='radio'] > label").on("click", function() {}

JS to add form fields with a button

How I create a do...while loop (or if there is a better way to go about this - please advise) for a form with potentially additional information?
Background - I've got a form that will accept a users assessment of a particular location (such as a basement). Using only 1 location per form, this works nicely and submits to my db without a problem.
Now I want to enhance this form with a "add new location" button. I don't (obviously) want to create new pages but rather a loop that can store the first location, save it (which I know could be done with be a session variable) and then clear the fields for locations 2, 3, 4, etc.
My confusion is around the functionality of the button. What type of button is this? Reset with a unique id such as new_loc[]?
And then when I write this as a do...while loop should I do it like this:
<?php
do {
all my form fields
} while (some condition that looks for the button submit);
?>
ok so I have a created a simple JS that can "handle" this.
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " locations");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><br><input type='text' name='location[]'>";
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
Now the problem is that JS will add 1 new field - any suggestions on how to add a massive block of HTML to the JS? I tried adding all my fields to the JS and I get a whole bunch of unclosed string errors.
So first of all your form must have action="" method="post"
then add this php to your page:
session_start();
if (isset ($_POST['NameOfSubmitButtonInsideForm'])) {
if (!isset ($_SESSION['sessionName'])) {
$_SESSION['sessionName'] = 1
}
for ($i = 0; $i <= $_SESSION['sessionName']; $i++) {
echo 'some html code like a form with a input that has
<input type="submit" name="submit- . $i .'EndInputTag>';
};
}
So this will loop the number of times the user clicked the button and you can echo out html code based on that number, or what ever it is you need to do in the loop.
Ok I've figured this out. Thanks to Marc B for suggesting JS.
HTML for the button
<input style="margin-left:5px;" class="btn btn-primary" type="button" value="Add Additional Location" onClick="addInput('locInformation');">
JS
var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<h3>Location " + (counter + 1) + "</h3>" + document.getElementById('additionalLoc').innerHTML;
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}
And then lastly is the new locInformation stuff:
<div id="additionalLoc" language="text">
huge block of HTML with additional fields
</div>

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?
function newBox
{
numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
var pizzaBoxCode = "<div class = 'PizzaBox'>"
+ " <h6>Box number " + numOfBoxes + "</h6>"
+ " <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
+ " <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
+ "</div>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
PizzaBoxHolder.innerHTML += pizzaBoxCode;
}
Any help is appreciated. Thanks!
The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.
var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder");
PizzaBoxHolder.appendChild(pizza);
Working fiddle.

Select menu behaving strangely with AJAX

I have a dropdown whose options get filled dynamically:
function populateDropdown(dropdownNum) {
// invokeWebService uses $.ajax
json = invokeWebService("GET", "/webservice/dropwdownOptions");
optionsHtml = "";
$.each(json, function(count, jsObj) {
optionValue = jsObj.name
optionsHtml+="<option>" + optionValue + "</option>";
});
var dropdownId = "#NRdropdown_" + dropdownNum;
$(dropdownId).html(optionsHtml);
}
function display(blockNum) {
var url = "/webservice/blocks" + blockNum;
var response = invokeWebService("GET", url);
var replacementHtml = "";
var currBlock = "blah";
$.each(response, function(i, block) {
currName = block.name;
var textfield = "<input type='text' id='blockValue" + block.id +
"'>";
var dropdownMenu = "<select id=\"NRdropdown_" + i +
"\"onClick=\"populateDropDown(" + i +
")\"><option>Existing Blocks</option>"
var submitButton = "<input type='submit' value='UPDATE' id='" +
block.id + "'><br><br>";
replacementHtml = currName + textfield + dropdownMenu + submitButton;
});
$("#main").html(replacementHtml);
}
The javascript function "populateDropdown(dropdownNum)":
Makes the ajax request
Parses the json response for the option values into an html string called optionsHtml
Replaces the inner html of the select element with the option values via:
var dropdownSelector = "#NRdropdown_" + dropdownNum;
$(dropdownSelector).html(optionsHtml)
1) When I click on the dropdown arrow, I STILL see "Existing Blocks".
2) After 1 sec I see the first dynamically generated option UNDERNEATH the "Existing Blocks" option, I don't see the other dynamically generated options.
3) Then I click outside the dropdown and see the dropdwon showing the first dynamically generated value.
4) Finally I click the dropdown arrow again and it works as it should with all the dynamically generated values.
How do I make it work so that:
When the page first loads, the dropdown shows "Existing Blocks".
Once I click the dropdown arrow, the dropdown should show all dynamically generated values without the "Existing Blocks" value.
Thanks!
the dropdown listener should be for onmousedown, not onclick

Categories

Resources