I've got list of products for my autocomplete and different pictures for them. How can I put the radiobuttons with pictures under each product? This is my code for autocomplete so far
function create_rbuttons(item){
var str = $();
if(item.PicId !=null){
for(i=0;i<item.PicId.length;i++){
debugger;
str = str + $('<input type="radio" name="rbtnCount" />');
}
}
return str;
}
$('.SliderBox').on("focus",function () {
$(this).autocomplete({
delay: 500,
minLength: #(Model.SearchTermMinimumLength.ToString()),
source: '#(Url.RouteUrl("ProductSearch"))',
select: function( event, ui ) {
$(this).val(ui.item.label);
var box_id = $(this).closest('.search-box').attr('value');
$('.Picture'+box_id+' img').attr('src',ui.item.productpictureurl).width(100).height(100);
$('#Picture'+box_id+'Id').attr('value',ui.item.PicId[0])
$('.Text'+box_id+' input').attr('value',ui.item.label)
$('.Link'+box_id+' input').attr('value',ui.item.producturl);
return false;
}
})
.data("ui-autocomplete")._renderItem = function( ul, item ) {
var t = item.label;
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>#(true ? Html.Raw("<img src='\" + item.UrlsArr[0] + \"'>") : null)" + t + "</a>")
.append("<a>" + t + "</a>")
.append(create_rbuttons(item))
.appendTo(ul);
};
PicId is an array, where I keep id of pictures. UrlsArr — where I keep paths to them
I tried something. The radio button doesn't really do anything, it just sits there.
But you can see the icon.
See if it helps
index.php
<style>
img.icon {
height: 20px;
}
.highlight {
color: red;
}
</style>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
var searchbox = $("#search");
searchbox.autocomplete({
source: "autocomplete.php",
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var li_item = highlight(searchbox.val(), item.value); // highlight
if(li_item.length) {
return $('<li></li>')
.data('item.autocomplete', item)
.append(' <input type="radio" name="rbtnCount"> <img class="icon" src="' + item.icon + '"> ' + li_item )
.appendTo(ul);
}
else {
return $('<li></li>');
}
};
// based on #see http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript
function highlight(needle, haystack) {
var result = haystack;
var index = haystack.toLowerCase().indexOf(needle.toLowerCase());
if ( index >= 0 ) {
result = haystack.substring(0, index) + "<span class='highlight'>" + haystack.substring(index, index+needle.length) + "</span>" + haystack.substring(index + needle.length);
}
else {
// no match
return '';
}
return result;
}
});
</script>
<input id="search">
autocomplete.php
[
{"value": "ActionScript", "icon": "http://blog.istorm.ca/wp-content/uploads/2011/05/64px-ActionScript_icon.png"},
{"value": "Boostrap", "icon": "http://qph.is.quoracdn.net/main-thumb-t-407834-50-bcwisowdvdkeethoagubojbfeljzwjwy.jpeg"},
{"value": "C++", "icon": "http://imag.malavida.com/mvimgbig/download-s/turbo-c-4955-0.jpg"},
{"value": "Jquery", "icon": "https://pbs.twimg.com/profile_images/59268975/jquery_avatar_normal.png"},
{"value": "Java", "icon": "https://pbs.twimg.com/profile_images/426420605945004032/K85ZWV2F_normal.png"},
{"value": "JavaScript", "icon": "http://www.kalmstrom.com/images/logos/Icons/JavaScript128.png"}
]
Try this
function create_rbuttons(item){
if(item.PicId !=null){
for(i=0;i<item.PicId.length;i++){
var radioBtn = $('<input type="radio" name="rbtnCount" />');
radioBtn.appendTo(ul);
}
}
}
Related
I just need to stop execution of function until the user conform OK or CANCEL in dialog box. If user clicks on OK it should continue the execution ..if he clicked on Cancel we should stop the execution.
How i can achieve this?
Below is my code:
function Verifivation() {
var messages = ['Custmer and Client is from Diff City'];
var OKFunction = function () {
$('#MessagesDialog').remove();
return true;
};
var cancelFunction = function () {
$('#MessagesDialog').remove();
};
createMessageDialog("Verification", "ReceptPage", messages, ["OK", "Cancel"], [OKFunction, cancelFunction], function () { }, null, null, getConfirmHandler);
}
function createMessageDialog(title, parentid, messages, buttonLabels, buttonFunctions, functPartialLoad, top, isModal, closeCallback) {
if (top == null || top == '') top = 80;
if (isModal == null) isModal = true;
var openFunc = function () {
if (typeof messages == "object") {
if (messages.length > 0) {
for (var i = 0; i < messages.length; i++) {
$("#messages").append("<span>" + messages[i] + "</span><br/>");
}
}
} else if (typeof messages == "string") {
$("#messages").append("<span>" + messages + "</span><br/>");
}
if ((buttonLabels.length > 0) && (buttonFunctions.length > 0) && (buttonLabels.length == buttonFunctions.length)) {
for (var i = 0; i < buttonLabels.length; i++) {
if (i == 0) {
$("#messageBtn").append("<button type='button' value='" + buttonLabels[i] + "'class='button green' id='" + buttonLabels[i].trim().replace(" ", "") + "Btn'><i class='fas fa-check-circle' style='margin-right: 3px !important'></i>" + buttonLabels[i].trim().replace(" ", "") + "</button> ");
}
else {
$("#messageBtn").append("<button type='button' value='" + buttonLabels[i] + "'class='button orange' id='" + buttonLabels[i].trim().replace(" ", "") + "Btn'><i class='fas fa-times-circle' style='margin-right: 3px !important'></i>" + buttonLabels[i].trim().replace(" ", "") + "</button> ");
}
$("#" + buttonLabels[i].trim().replace(" ", "") + "Btn").click(buttonFunctions[i]);
}
}
functPartialLoad();
};
$("#" + parentid).append('<div id="MessagesDialog" title="' + title + '" style="display: none"><div id="messages"></div><div id="partialContent"></div><div id="messageBtn" style="margin-top: 5px; text-align:center;"></div></div>');
$("#MessagesDialog").dialog({
autoOpen: true,
heigt: 500,
width: 500,
position: ['top', top],
modal: isModal,
close: function (event, ui) {
$(this).remove();
if (closeCallback)
closeCallback();
},
open: openFunc
})
}
function openDialog() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
executeNow();
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
function executeNow(){
console.log("I am executing");
};
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Dialog - Modal confirmation</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="dialog-confirm" title="Empty the recycle bin?" style="display:none;">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<p onclick="openDialog()">click me to open dialog</p>
</body>
</html>
I'm making a basic shopping list app and have run into a wall. The program silently fails, and upon checking with breakpoints and such, I've discovered that on line 75, I'm getting newItem as undefined.
Everything else in the statement is being defined correctly. Any clue what I've done wrong?
Here's the index.js:
'use strict';
var state = {
items: []
};
var listItemTemplate = (
'<li>' +
'<span class="shopping-item js-shopping-item"></span>' +
'<div class="shopping-item-controls">' +
'<button class="js-shopping-item-toggle">' +
'<span class="button-label">check</span>' +
'</button>' +
'<button class="js-shopping-item-delete">' +
'<span class="button-label">delete</span>' +
'</button>' +
'</div>' +
'</li>'
);
// state modification functions
var stateHelper = {
addItem: function(state, item) {
state.items.push({
displayName: item,
checkedOff: false
});
},
getItem: function(state, itemIndex) {
return state.items[itemIndex];
},
deleteItem: function(state, item) {
state.items.splice(itemIndex, 1);
},
updateItem: function(state, item) {
state.items[itemIndex] = newItemState;
}
}
// render functions
var renderHelper = {
renderItem: function(item, itemId, itemTemplate, itemDataAttr) {
var element = $(itemTemplate);
element.find('.js-shopping-item').text(item.displayName);
console.log("item.displayName: " + item.displayName)
console.log("item: " + item)
if (item.checkedOff) {
element.find('.js-shopping-item').addClass('shopping-item__checked');
}
element.find('.js-shopping-item-toggle')
element.attr(itemDataAttr, itemId);
// try `element.find('.js-shopping-item-toggle').attr(itemDataAttr, itemId);` instead and see if it works
console.log("itemDataAttr: " + itemDataAttr)
return element;
},
renderList: function(state, listElement, itemDataAttr) {
var itemsHTML = state.items.map(
function(item, index) {
//what determines the index here?
console.log("index: " + index)
return renderItem(item, index, listItemTemplate, itemDataAttr);
});
listElement.html(itemsHTML);
}
}
// event listeners
var eventHelper = {
handleItemAdds: function(formElement, newItemIdentifier, itemDataAttr, listElement, state) {
formElement.submit(function(event) {
event.preventDefault();
var newItem = formElement.find(newItemIdentifier).val();
console.log(newItem)
stateHelper.addItem(state, newItem);
console.log(newItemIdentifier)
this.reset();
});
},
handleItemDeletes: function(formElement, removeIdentifier, itemDataAttr, listElement, state) {
listElement.on('click', removeIdentifier, function(event) {
var itemIndex = parseInt($(this).closest('li').attr(itemDataAttr));
console.log("this: " + this);
console.log("$(this).closest('li').attr(itemDataAttr " + $(this).closest('li').attr(itemDataAttr));
stateHelper.deleteItem(state, itemIndex);
renderList(state, listElement, itemDataAttr);
console.log("what is itemDataAttr? it is: " + itemDataAttr)
})
},
handleItemToggles: function(listElement, toggleIdentifier, itemDataAttr, state) {
listElement.on('click', toggleIdentifier, function(event) {
var itemId = $(event.currentTarget.closest('li')).attr(itemDataAttr);
var oldItem = stateHelper.getItem(state, itemId);
stateHelper.updateItem(state, itemId, {
displayName: oldItem.displayName,
checkedOff: !oldItem.checkedOff
});
renderHelper.renderList(state, listElement, itemDataAttr)
});
}
}
$(function() {
var formElement = $('#js-shopping-list-form');
var listElement = $('.js-shopping-list');
//id of input containing list items
var newItemIdentifier = "#js-new-item";
//in listItemTemplate above; the delete button has this class
var removeIdentifier = ".js-shopping-item-delete";
//stores id of list item
var itemDataAttr = "data-list-item-id";
var toggleIdentifier = ".js-shopping-list-toggle"
eventHelper.handleItemAdds(formElement, newItemIdentifier, itemDataAttr, listElement, state);
eventHelper.handleItemDeletes(formElement, removeIdentifier, itemDataAttr, listElement, state);
eventHelper.handleItemToggles(listElement, toggleIdentifier, itemDataAttr, state);
});
And here's the index.html for reference:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Shopping List</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<h1>Shopping List</h1>
<form id="js-shopping-list-form">
<label for="shopping-list-entry">Add an item</label>
<input type="text" name="shopping-list-entry" id="shopping-list-entry" placeholder="e.g., broccoli">
<button type="submit">Add item</button>
</form>
<ul class="shopping-list">
</ul>
</div>
<script src="jquery-3.1.1.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
Alacritas,
I don't see anywhere in your view that you actually have an element with an id that matches that accessor (#js-new-item).
Your comment says it belongs to the input box, but the input box you have in your html does not have that id.
I think you would need to update the string "#js-new-item" to be "#shopping-list-entry".
update
I need to be able to reference the XML from my actual XML document, i dont want it just var'd into jQuery...
How do i get the following behaviour to occur...
Searching the label input searches for both label and value, however, only omits results from each to their respective input field so typing Alabama shows Alabama - AL but only gives me Alabama in state and AL in value
also using
$.ajax({
type: "GET",
url: "states.xml", // change to full path of file on server
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
instead of the var myXML
var myXml = '<?xml version="1.0" encoding="UTF-8"?><states><state label=Alabama value=AL country="US"><state label=Alaska value=AK country="US"></states>';
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
</script>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
We have to follow this logic: After autocomplete selects value, we have to to check if values for other two fields are unique in their scope. For example, selecting country-code CA (xml value attribute) has unique label California, as well as unique country US. If the values is not unique, than we erase that input value. The checking function name is fillIfUnique(), take a look at this Fiddle.
HTML used:
<h3>jQuery Autocomplete using XML as Data Source Example</h3>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
Script:
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
Notes: I had to compress and insert XML into script. I removed duplicate entries in arrays.
Updating with full code below. Also adjusting question.
What happens? After all questions are answered endQuiz triggers and gives the user a score. A form also appears which I want the user to fill out and send to a specific e-mail account. But when I fill out the form and press "send" when the quiz is run on my company's server I 1) get a 405 error. When I run this locally nothing happens.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var quiztitle = "quiz title";
var quiz = [
{
"question" : "q1",
"image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
"choices" : [
"a1",
"a2",
"a3",
"a4"
],
"correct" : "a2",
"explanation" : "good job"
},
{
"question" : "q2",
"image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
"choices" : [
"a1",
"a2"
],
"correct" : "a2",
"explanation" : "good job"
},
{
"question" : "q3",
"image" : "http://www.saferinternet.org/image/image_gallery?uuid=b243b830-e3fd-49b9-ad2c-43b2ff073db8&groupId=10137&t=1359909134797",
"choices" : [
"a1",
"a2",
"a3",
"a4"
],
"correct" : "a3",
"explanation" : "good job"
}
];
var currentquestion = 0,
score = 0,
submt = true,
picked;
$(document).ready(function(){
$("#submitbutton").hide();
function htmlEncode(value) {
return $(document.createElement('div')).text(value).html();
}
function addChoices(choices) {
if (typeof choices !== "undefined" && $.type(choices) == "array") {
$('#choice-block').empty();
for (var i = 0; i < choices.length; i++) {
$(document.createElement('li')).addClass('choice choice-box').attr('data-index', i).text(choices[i]).appendTo('#choice-block');
}
}
}
function nextQuestion() {
submt = true;
//alert("nQ");
$('#explanation').empty();
$('#question').text(quiz[currentquestion]['question']);
$('#pager').text('Q ' + Number(currentquestion + 1) + ' of ' + quiz.length);
if (quiz[currentquestion].hasOwnProperty('image') && quiz[currentquestion]['image'] != "") {
if ($('#question-image').length == 0) {
$(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question'])).insertAfter('#question');
} else {
$('#question-image').attr('src', quiz[currentquestion]['image']).attr('alt', htmlEncode(quiz[currentquestion]['question']));
}
} else {
$('#question-image').remove();
}
addChoices(quiz[currentquestion]['choices']);
setupButtons();
}
function processQuestion(choice) {
//alert(choice);
currentquestion++;
//alert(currentquestion);
$("#submitbutton").hide();
if (currentquestion == quiz.length) {
endQuiz();
} else {
nextQuestion();
}
}
function setupButtons() {
$('.choice').on('mouseover', function () {
$(this).css({
'background-color': '#e1e1e1'
});
});
$('.choice').on('mouseout', function () {
$(this).css({
'background-color': '#fff'
});
})
$('.choice').on('click', function () {
//alert("");
choice = $(this).attr('data-index');
$('.choice').remove();
if (quiz[currentquestion]['choices'][choice] == quiz[currentquestion]['correct']) {
$('.choice').eq(choice).css({
'background-color': '#50D943'
});
$('#explanation').html('<p style="background-color:green;">Score! <strong>' + quiz[currentquestion]['correct'] + 'Thats the right answer!</p>' + htmlEncode(quiz[currentquestion]['explanation']));
score++;
} else {
$('.choice').eq(choice).css({
'background-color': '#D92623'
});
$('#explanation').html('<p style="background-color:red;">Sorry!' +quiz[currentquestion]['choices'][choice] + 'Thats the wrong answer!</p>' + htmlEncode(quiz[currentquestion]['explanation']));
}
$("#submitbutton").show();
if (submt) {
////alert("submit");
submt = false;
$('#submitbutton').css({
'color': '#000'
});
$("#submitbutton").click(function(){
////alert("click");
$('.choice').off('click');
$(this).off('click');
processQuestion(choice);
});
}
})
}
function endQuiz() {
$('#explanation').remove();
$('#question').empty();
$('#choice-block').remove();
$('#submitbutton').remove();
$('#question-image').remove();
if (score > 2) {
$('#question').text("best " + score + " of " + quiz.length + " correct.");
}
if (score > 1 && score < 3) {
$('#question').text("ok " + score + " of " + quiz.length + " correct.");
}
if (score < 2) {
$('#question').text("poor " + score + " of " + quiz.length + " correct.");
}
if (score < 1) {
$('#question').text("worst " + score + " of " + quiz.length + " correct.");
}
$(document.createElement('h2')).css({
'text-align': 'center',
'font-size': '4em'
}).text(Math.round(score / quiz.length * 100) + '%').insertAfter('#question');
$(document.createElement('form')).addClass('form').attr({method:'post', action:'mail.php', id: 'form'}).html('Please fill out the form').appendTo('#frame');
$("<input type='text' name='yourname' id='yourname' placeholder='Your name' />").appendTo('.form');
$("<input type='text' name='municipality' id='municipality' placeholder='Your municipality' />").appendTo('.form');
$("<input type='text' name='email' id='email' placeholder='Your e-mail' />").appendTo('.form');
$(document.createElement('header')).addClass('formheader').text('Give your municipality a point!').appendTo('.form');
$("<input type='radio' name='points' id='points1' title='1' value='1' />").appendTo(".form");
$("<label for='points1' />").text('1').appendTo('.form');
$("<input type='radio' name='points' id='points2' title='2' value='2' />").appendTo('.form');
$("<label for='points2' />").text('2').appendTo('.form');
$("<input type='radio' name='points' id='points3' title='3' value='3' />").appendTo('.form');
$("<label for='points3' />").text('3').appendTo('.form');
$("<input type='radio' name='points' id='points4' title='4' value='4' />").appendTo('.form');
$("<label for='points4' />").text('4').appendTo('.form');
$("<input type='radio' name='points' id='points5' title='5' value='5' />").appendTo('.form');
$("<label for='points5' />").text('5').appendTo('.form');
$(document.createElement('textarea')).addClass('mail_text').attr('id', 'text_mail').text('Please send us your story!').appendTo('.form');
$("<input type='submit' id='sendForm' class='sendForm' name='sendForm' value='Press to send!'/>").appendTo('.form');
}
function sendForm() {
$('#form').submit(function(event){
$('#sendForm').attr('value','Your answer was sent!');
setTimeout(function(){
$('#sendForm').attr('value','Sending...');
}, 2000);
var stuff = $('#form').serialize();
jQuery.ajax({
type: 'POST',
url: 'mail.php',
data: stuff,
dataType: "json"
});
//Prevents form submission
return false;
});
}
function init() {
//add title
if (typeof quiztitle !== "undefined" && $.type(quiztitle) === "string") {
$(document.createElement('h1')).text(quiztitle).appendTo('#frame');
} else {
$(document.createElement('h1')).text("Quiz").appendTo('#frame');
}
//add pager and questions
if (typeof quiz !== "undefined" && $.type(quiz) === "array") {
//add pager
$(document.createElement('p')).addClass('pager').attr('id', 'pager').text('Q 1 of ' + quiz.length).appendTo('#frame');
//add first question
$(document.createElement('h2')).addClass('question').attr('id', 'question').text(quiz[0]['question']).appendTo('#frame');
//add image if present
if (quiz[0].hasOwnProperty('image') && quiz[0]['image'] != "") {
$(document.createElement('img')).addClass('question-image').attr('id', 'question-image').attr('src', quiz[0]['image']).attr('alt', htmlEncode(quiz[0]['question'])).appendTo('#frame');
}
$(document.createElement('p')).addClass('explanation').attr('id', 'explanation').html(' ').appendTo('#frame');
//questions holder
$(document.createElement('ul')).attr('id', 'choice-block').appendTo('#frame');
//add choices
addChoices(quiz[0]['choices']);
//add submit button
$(document.createElement('div')).addClass('choice-box').attr('id', 'submitbutton').text('Nästa fråga').css({
'font-weight': 700,
'color': '#222',
'padding': '30px 0',
}).appendTo('#frame');
$("#submitbutton").hide();
setupButtons();
}
}
init();
});
</script>
</head>
<body>
<div id = "frame" role = "content"></div>
</body>
</html>
mail.php
<?php parse_str($_POST['stuff']); mail("test#mymail.org", "Title", "$yourname, $email, $points, $text_mail"); ?>
Your jQuery selectors seem to be mis-matched.
You are looking for .sendForm class on the submit handler, but your form attribute is ID'ed as #sendForm with a class of .submitForm
then you do it again, your form is CLASSED as .form from the addClass() method on create, but then you are trying to send #form Id's data, which doesn't exist.
$(document.createElement('form')).addClass('form')
vs
stuff = $('#form').serialize();
It exaplins why nothing happes, as you aren't linking the elements to what you expect to have come in.
Original Example
Failed Example
Here's the returned data:
var availableTags = [
'ActionScript|AppleScript|Asp',
'BASIC',
'Clojure|C++|C|COBOL|ColdFusion',
'Erlang',
'Fortran',
'Groovy',
'Haskell',
'Java|JavaScript',
'Lisp',
'Perl|PHP|Python',
'Ruby',
'Scala|Scheme',
];
How can I split the items into arrays during the renderItem function,and when users type PHP it will only return PHP from 'Perl|PHP|Python'?
Here's my code:
$('#tags').autocomplete({
source: availableTags,
search: function(event, ui) {
$('#wrapper').empty();
},
})
.data('autocomplete')._renderItem = function(ul, item) {
return $('<div class="element"></div>')
.data('item.autocomplete', item)
var smallchoice = item.label.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = '<a href="#" >' + smallchoice+ '</a>'
})
.append($option)
.appendTo($('#wrapper'));
};
Here is an example of what you trying to do.
.data('autocomplete')._renderItem = function(ul, item) {
var inp = $("#tags").val();
var items = item.label.split("|");
for (var i = 0; i < items.length; i++) {
index = items[i].toUpperCase().indexOf(inp.toUpperCase());
if (index == 0 || index > 0) {
item = items[i];
return $('<div class="element"></div>')
.data('item.autocomplete', item)
.append('' + item + '')
.appendTo($('#wrapper'));
}
}
};
JSFiddle