I'm dynamically creating several vertically grouped radio buttons using jQuery mobile 1.0 for a multiple choice quiz.
When I paste this code from the JQM Radio Button Docs in it styles the controlgroup properly.
<fieldset data-role="controlgroup">
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
</fieldset>
When I dynamically inject my markup on pageshow() it injects the proper markup but it doesn't style the control group at all.
$.getJSON("assets/json/aircraft.json", function (data) {
var maxQuestions = 10;
var maxChoices = 4;
var randomsorted = data.aircraft.sort(function (a, b) {
return 0.5 - Math.random();
});
var quiz = $.grep(randomsorted, function (item, i) {
return i < (maxQuestions * maxChoices);
});
var arr_quiz_markup = [];
$.each(quiz, function (i, item) {
var q = Math.floor(i / maxChoices);
var c = i % maxChoices;
if (c == 0) arr_quiz_markup.push("<div>Image for question " + q + " goes here...</div><fieldset data-role='controlgroup' data-question='" + q + "'>");
arr_quiz_markup.push("<input type='radio' name='q" + q + "' id='q" + q + "c" + c + "' data-aircraftid='" + item.id + "' />");
arr_quiz_markup.push("<label for='q" + q + "c" + c + "'>" + item.name + "</label>");
if (c == maxChoices - 1 || c == quiz.length - 1) arr_quiz_markup.push("</fieldset><br />");
});
$("#questions").html(arr_quiz_markup.join("")).controlgroup("refresh");
});
I tried $("#questions :radio").checkboxradio("refresh"); but throws "cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'".
My Live Quiz Demo (Sorry, jsfiddle doesn't have jQuery Mobile listed)
What am I doing wrong? How do I refresh this to properly get JQM to style the controlgroup correctly?
Add this line
$("#quiz").trigger("create");
after
$("#questions").html(arr_quiz_markup.join("")).controlgroup("refresh");
This code snippet will force a rebuild of the quiz page so that jqm styles will be applied to the page contents.
You will get more information about the dynamic in this jQuery Forum thread.
The jQuery Mobile default styles will be applied once you use the following code. That's what I found and it's working for me.
$("input[type='radio']").checkboxradio().checkboxradio("refresh");
This works for me (I'm using jQuery Mobile 1.4.0):
HTML
<div id="locations" data-role="controlgroup"></div>
JS
$.ajax({
...
success: function(data, textStatus, jqXHR) {
// Hide loading message
$.mobile.loading("hide");
// Build page
$("#location-page").trigger("create");
// Clear another previos radio options
$("#locations").controlgroup("container")["empty"]();
// Read XML response
var rows = $("Row", data);
$(rows).each(function(index, value) {
var locationId = $("LocationID", this).text();
var locationName = $("LocationName", this).text();
var $el = $("<label for=\"location" + index + "\">" + locationName + "</label><input type=\"radio\" name=\"location\" id=\"location" + index + "\" value=\"" + locationId + "\">")
$("#locations").controlgroup("container")["append"]($el);
$($el[1]).checkboxradio();
});
$("#locations").controlgroup("refresh");
// Change to locations' page
$.mobile.changePage("#location-page", {transition: "flip"});
},
...
});
Related
We are trying to get a Quiz written in Javascript running on our site. We need to remove Radio buttons because currently, they are not linking through to the next question.
Here is the page in question:
http://stephanieshipper.com/test/
And below is the piece of code from the .js file that contains the Radio buttons. How would I remove these without breaking the rest of the functionality? So far, when I have taken out the Radio buttons, the text links also break.
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 {
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>")
}
I am working on a script to add a row to a form using js.
this is the js script I have.
<script>
jQuery(function($) {
var $button = $('#add-row'),
$row = $('.timesheet-row').clone();
$button.click(function() {
$row.clone().insertAfter('#clone-row');
});
});
</script>
Then my form's elements are set up like this.
<div class="form-group col-lg-2">
<label>In Time</label>
<input class="form-control" type="datetime" id="intime" name="intime[]">
</div>
My problem is I cant seem to figure out how to retrieve the values of the form fields
here is the jfiddle
jfiddle
Updated jfiddle to revised code to post to php file
<?php
$pos= $_POST['position'];
$position = json_decode($pos);
echo $position;
echo "This should work";
If anymore than one line is found no response is returned.
Basically you'll need to iterate through the elements to get their values.
.each() will help you in that.
select an element input or select with their name and call .each() on it.
In .each() fetch the value of current element and store it.
Here's the updated jsFiddle.
I took the liberty of adding a button(id = "get-row-values") on whose click you'll see an alert with all the values of your inputs and selects in .timesheet-row.
Also I removed [] from the names of your inputs and selects.
$("#get-row-values").click(function () {
var position = "";
var unit = "";
var employee = "";
var intime = "";
var outtime = "";
$(".timesheet-row select[name=position]").each(function () {
position += " " + $(this).val();
});
$(".timesheet-row select[name=unit]").each(function () {
unit += " " + $(this).val();
});
$(".timesheet-row select[name=employee]").each(function () {
employee += " " + $(this).val();
});
$(".timesheet-row input[name=intime]").each(function () {
intime += " " + $(this).val();
});
$(".timesheet-row input[name=outtime]").each(function () {
outtime += " " + $(this).val();
});
alert("Positions : " + position + "\nUnits : " + unit + "\nEmployees : " + employee + "\nIntimes : " + intime + "\nOuttimes : " + outtime);
});
So i have a page that has a couple of jQuery plugins. Among other things i have the multiselect toolbar, a pretty sweet plugin. problem is that when i load up the page in internet explorer the page breaks. i've been able to determine that the problem occurs when i try to set some attributes to some elements that i have dynamically generated.
here is the code for generating the elements:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
var tvrtke = data.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("KlijentMultiSelect").innerHTML +=
"<option value=\"" + tvrtke[i] + "\" id=\"" + tvrtke[i] + "\" >" + tvrtke[i] + "</option>";
}
$("#KlijentMultiSelect").multiselect({
selectedText: "",
height: 125,
minWidth: 650,
noneSelectedText: 'Izaberite željene tvrtke:'
});
}
});
the function gets the correct data and generates the options, and then i activate the plugin to render the new dropdown menu with checkboxes.
problem is that afterwards i have this code:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).checked = true;
}
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).setAttribute("onclick", "ChangeTextKlijent()");
}
here i am trying to set the checkbox values to true and add an on click event to the input element, but then visual studio sends me the error message from the title. in firefox, everything works great but IE is a whole different story.
anyone know how to fix this?
I switched so that my code looks like this:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + value + "\" >" + value + "</option>");
});
and now it works.
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');