Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a web page that receives the following JSON from a server
{"d":[
{"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
{"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS "}
]}
From the array d in this data I need to create checkboxes, each corresponding to an element of the array, defined by the operators property of each element. I need these checkboxes to be dynamically generated with JavaScript/jQuery once the data is received. How can this be done?
Is this what you want?
var input=//get input json
var data=input.d;
for(var x in data){
var type=data[x].__type;
var ops=data[x].operators;
var id="checkbox-"+ops+Math.floor(Math.random()*100000);
$("<div><label></label><input/></div>")
.children().eq(1)
.attr({
"type":"checkbox",
"name":"insert here",
"data-type":type,
"data-operators":ops,
"id":id,
"class": "your checkbox class here"
})
.click(function(){ /////////////////////////// updated here
if($(this).prop("checked")){
// do action for checked event
} else {
// do action for unchecked event
}
})
.parent()
.children().eq(0)
.attr("for", id)
.text("whatever label you want")
.parent()
.appendTo($("container you want to put them in"));
}
You should loop over JSON result and create checkbox element and add it to div. Use jquery .each() to loop JSON. Try this:
var json = {"d":[
{"__type":"Service1.Operators:#MobileWCFService","operators":"ACCOUNTING"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AHOFFMAN"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"AMONROY"},
{"__type":"Service1.Operators:#MobileWCFService","operators":"APATENTAS "},
{"__type":"Service1.Operators:#MobileWCFService","operators":"WRAMOS "}
]};
$(document).ready(function() {
var $grouplist = $('#checkboxes');
$.each(json.d, function() {
$('<label>'+this.operators+': </label><input type=checkbox
value='+this.operators+'/>').appendTo($grouplist);
});
});
DEMO
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
I have been struggling with this issue for a couple of days now...
In my home view I have a group of two buttons that are linked to another controller "BookingController". these two buttons have a variable id, that changes based on the value stored in the database. So what I wanna do is when the user click the first button "start button" a new record will be added in the "booking" table in database and one of the values that will be sotred in this record is the id of the element clicked. The problem is I can't figure a way to pass this id to the controller where I will use it in "addBooking" function. I would like to pass the id value to the function as a whole and modify the string in the controller function itself or after modifying it as a string here in the javascript.
here is the code simplified
`
#php
use App\Http\Controllers\BookingController;
#endphp
#push('js')
<script>
function reply_click(clicked_id)
{
if (clicked_id.indexOf(startTime) !== -1)
{
var roomID= clicked_id.replace("btnStart","");
** var booking = " <?php BookingController::addBooking(); ?> ";** <---- I want to pass the "roomID" var into "addBooking" function here
}
else if (clicked_id.indexOf(endTime) !== -1)
{
var roomID= clicked_id.replace("btnEnd","");
var booking = " <?php BookingController::updateBooking(); ?> ";
}
}
</script>
#endpush
#section('content')
<div class="btn-group">
<button onClick="reply_click(this.id)" id="btnStart{{ $room->id }}" type="button"></button>
<button onClick="reply_click(this.id)" id="btnEnd{{ $room->id }}" type="button"></button>
</div>
#endsection
`
I tried couple of ways but still not getting the value passed. I tried the cookies and it's working but it keeps adding the same record on each reload. I also tried the following
$.post ('app\Http\Controllers\BookingController.php', {room: roomID});
$.ajax ({ type: 'post', url: 'app\Http\Controllers\BookingController.php', data: {room= roomID}, sucess: function (data) { console.console.log(data);} });
'app\Http\Controllers\BookingController.php' is not a url. Use a valid url to point to your controller method.
Your ajax code should be something like this. I don't know what your route looks like, so point to the correct route.
$.ajax ({ method: 'post', url: '/booking/update', data: {room: roomID}, success: function (data) { console.log(data); } });
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
$("#yl").click(function(){updateYear("sub")});
$("#yr").click(function(){updateYear("add")});
$("#ml").click(function(){updateMonth("sub")});
$("#mr").click(function(){updateMonth("add")});
$("#dl").click(function(){updateDay("sub")});
$("#dr").click(function(){updateDay("add")});
Is there a way to write this code cleaner, smarter without repetitions?
If you change your elements a bit, you could do something like this:
<button id='yr' data-type='update' data-date-part='year' data-date-action='add'>
Then you create an update function that starts off like this:
function update() {
const el = $(this);
const datePart = el.attr('data-date-part');
const dateAction = el.attr('data-date-action');
// do your logic to update the date based on what part and action
}
Then your click handler just needs to be:
$('button[data-type="update"]').click(update);
I forgot to mention, that newer versions of jquery will also let you just use the .data() function instead of spelling out the full data- attribute
The code is fine as it stands as it is very clear what is happening.
If you really want to do it differently, then you should probably also modify your function(s) and look into HTML attributes. It all depends what you are actually doing in those functions.
If for instance you want the user to enter a date just by pressing add/sub buttons, then the basics could look like this:
$('.change-value').click(updateDatePart);
function updateDatePart() {
// Read current date
var dateParts = $.map($(this).closest(".dateinput").find(".part-value"), function (span) {
return +$(span).text();
});
// Which part of the date needs incrementing/decrementing?
var part = $(this).closest('.part').index();
// Apply change to that part
dateParts[part] += $(this).data("inc");
// Create a date with this
var date = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
// Get the parts for the new date (which may have resolved some overflow)
dateParts = [date.getFullYear(), date.getMonth()+1, date.getDate()];
// Output the result
$('.part-value').each(function (i, elem) {
$(elem).text(dateParts[i]);
});
}
.change-value { font-size: 50% }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="dateinput">
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">2017</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">12</span>
<button class="change-value" data-inc="1">+</button>
</span>-
<span class="part">
<button class="change-value" data-inc="-1">-</button>
<span class="part-value">24</span>
<button class="change-value" data-inc="1">+</button>
</span>
</span>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
function createProductCodeForm(parent) {
var form = $("<form/>");
form.append($("<label>").text('Product Code:'));
form.append($("<input>").attr('name', 'productCode').attr('type', 'text'));
form.append($("<label>").attr('name', 'hint').text('The product code can be found on the label.'));
form.append('<br>');
form.append($("<input>").attr('type', 'submit'));
parent.append(form);
}
The createProductCodeForm function is used to create a new form that accepts a product code from a user.
The current version of the form contains the hint: 'The product code can be found on the label'. This hint is currently always visible to the user.
Improve the form so that the hint is only rendered when the input element is the focused element.
Im having a problem getting this question done since I have little experience with jquery and most of this test has been with javascript / php.
You can just bind the right attributes to get this all done:
function createProductCodeForm(parent) {
var form = $("<form/>");
form.append($("<label>").text('Product Code:'));
form.append($("<input>").attr('name', 'productCode').attr('type', 'text').attr('onfocus','$("label[name]").show()').attr('onblur','$("label[name]").hide()'));
form.append($("<label>").attr('name', 'hint').text('The product code can be found on the label.').attr('style','display:none'));
form.append('<br>');
form.append($("<input>").attr('type', 'submit'));
parent.append(form);
}
Codepen: https://codepen.io/YasirKamdar/pen/xYJdNy
You will have to create event handlers for the focus/blur events:
function createProductCodeForm(parent) {
var form = $("<form/>");
var input = $("<input>")
.attr('name', 'productCode')
.attr('type', 'text');
var label = $("<label>")
.attr('name', 'hint')
.text('The product code can be found on the label.')
.hide();
form.append($("<label>").text('Product Code:'));
form.append(input);
form.append(label);
input.focus(label.show.bind(label));
input.blur(label.hide.bind(label));
form.append('<br>');
form.append($("<input>").attr('type', 'submit'));
parent.append(form);
}
createProductCodeForm($('#formContainer'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="formContainer"></div>
You can use the Bootstrap plugin to do the task.
function createProductCodeForm(parent) {
var form = $("<form/>");
form.append($("<label>").text('Product Code:'));
var $productCode = $('<input />');
$productCode.attr({'name' : 'productCode', 'type': 'text'});
// use Bootstrap tooltip plugin:
$productCode.tooltip({'trigger':'focus', 'title': 'The product code can be found on the label.', 'placement':'right'});
form.append($productCode);
form.append('<br>');
form.append($("<input>").attr('type', 'submit'));
parent.append(form);
}
createProductCodeForm($('body'))
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
I think for the element in html should set the class or id to confirm the correct object(ex input:txtInput ,label :lblHint). So I think the code should look like this:
function createProductCodeForm(parent) {
var form = $("<form></form>");
form.append($("<label>").text('Product Code:'));
form.append($("<input>").attr('name', 'productCode').attr('type', 'text').attr('id', 'txtInput'));
form.append($("<label>").attr('name', 'hint').css("display", "none").attr('id', 'lblHint').text('The product code can be found on the label.'));
form.append('<br>');
form.append($("<input>").attr('type', 'submit'));
parent.append(form);
$("#txtInput").focusin(function() {
$("#lblHint").show();
});
$("#txtInput").focusout(function() {
$("#lblHint").hide();
});
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Dear Friends of StackOverflow,
I need to make the following HTML markup entry to a definition list "DL" thru Javascript so i can make the entry dynamically. Also need to edit the CSS Values. I will put the CSS entry after the HTML. In the dd entry there is a class, an anchor with class, an href, some text, another anchor with class, and href. I don't know the proper syntax to enter these thru Javascript. Many thanks for any help. Markandeya
<dt class="Book2"><span>Book2</span></dt>
<dd class="Book2"><a class="amazonLink" href="http://www.amazon.co.uk/Principles-Beautiful-Web-Design/dp/0975841963%3FSubscriptionId%3DAKIAJCFYSPA5V4ZSCM6Q%26tag%3Dstevwork-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0975841963"><img src="http://ecx.images-amazon.com/images/I/41FxC9u%2B%2BVL._SL160_.jpg" alt=""></a><br>
<strong>Beautiful Web Design</strong> by Jason Beaird.<br>
This book teaches you a wide range of topics on how to make great web sites, covering layout styles, ratios and colour theory.<br>
<a class="publisherLink" href="#">Beautiful Web Design on SitePoint</a>
</dd>
CSS hard code for the class "Book2" is: ( need syntax to edit entries thru Javascript)
dl.bookshelf dt.Book2 {
background: url(img/beautdesign-spine.png) 0 0 no-repeat,
url(img/beautdesign-front.png) 40px 0 no-repeat;
left:52px;
width:280px;
z-index:2;
}
Not exactly the same style output. The publisher field can be left off, and an image is not required for the store link. You can also set the class from the JSON object for the store link. The desc is an array, which is converted into a series of paragraphs. This may not be exactly what you want, but it should at least provide a good running start.
First, the Javascript:
var books = [
{
title: 'Beautiful Web Design',
author: 'Jason Beaird',
link: {
cls: 'amazonLink',
href: 'http://www.amazon.co.uk/Principles...',
img: 'http://ecx.images-amazon.com/images/...',
text: 'View on Amazon'
},
publisher: {
href: '#',
name: 'SitePoint'
},
desc: [
'This book teaches you...'
]
}
];
var bookshelf = document.getElementById('bookshelf');
for(var i=0,l=books.length;i<l;i++) {
var book = books[i];
var dt = document.createElement('dt');
var title = document.createElement('strong');
title.appendChild(document.createTextNode(book.title));
dt.appendChild(title);
dt.appendChild(document.createTextNode(' by ' + book.author));
var dd = document.createElement('dd');
if(book.link.href !== null) {
var link = document.createElement('a');
link.setAttribute('class',book.link.cls);
link.setAttribute('href',book.link.href);
if(book.link.img !== undefined && book.link.img !== null) {
var img = document.createElement('img');
img.setAttribute('src',book.link.url);
img.setAttribute('alt',book.link.text);
link.appendChild(img);
}
else {
link.appendChild(document.createTextNode(book.link.text));
}
dd.appendChild(link);
}
if(book.desc !== undefined && book.desc instanceof Array) {
for(var j=0,k=book.desc.length;j<k;j++) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(book.desc[j]));
dd.appendChild(p);
}
}
if(book.publisher !== undefined) {
var pub = document.createElement('a');
pub.setAttribute('class','publisherLink');
pub.setAttribute('href',book.publisher.href);
pub.appendChild(document.createTextNode(book.title + ' on ' + book.publisher.name));
dd.appendChild(pub);
}
bookshelf.appendChild(dt);
bookshelf.appendChild(dd);
}
Next, the HTML output:
<dl id="bookshelf">
<dt>
<strong>Beautiful Web Design</strong> by Jason Beaird
</dt>
<dd>
<a class="amazonLink" href="..."><img src="..." alt="View on Amazon"/></a>
<p>
This book teaches you...
</p>
<a class="publisherLink" href="#">Beautiful Web Design on SitePoint</a>
</dd>
</dl>
You can probably add classes and elements here or there to make the resultant HTML more descriptive and more responsive to CSS.
I have to write a simple quiz app. As I picked it after someone this is what I have.
There are 10 questions with 3 answers each. All question are loaded at once and only one visible. After clicking the answer next question shows up etc.
However as javascript is kinda magic to me I have no clue how to get all answers and send it to php to check if user chose correct.
The code looks something like this:
<form action="result.php">
<div class=“quiz>
<div class=“question”> Some question ?
<ul>
<li><a href=“#”>Answer A</a></li>
<li><a href=“#”>Answer B</a></li>
<li><a href=“#”>Answer C</a></li>
</ul>
</div>
[… more question here …]
<div class="question">Last question ?
<ul>
<li>Answer A</li>
<li>Answer B</li>
<li>Answer C</li>
</ul>
</div>
</div>
<input type=“hidden” name=“answers” value=“answers[]>
</form>
So basically user click on answer, next question pop up and at the end I need to populate all answer and send it to result.php where somehow I would get results within array with chosen answers like {1,3,2,1,2,3,1,2,3,1} or something like that.
There are many ways to accomplish this. Here's an easy one:
add a
<input type="hidden" name="questions[]" value="" />
inside each .question DIV
update the value of this input when one of the links are clicked:
$('.question a').on('click', function(){
var answer = $(this).text();
$(this).parents('.question').find('input').val(answer);
});
put a request method on your form, let's say POST
Then in your PHP script you'll get a numerically indexed array with the selected answer for each question, $_POST['questions'].
I do not know how your design looks like, but it may be possible to achieve this without any javascript, using hidden radio inputs and labels (I'm assuming here you're using links because of styling limitations on input fields).
Normally, you would create an HTTP request to your verification back-end. jQuery, for one, makes this quite easy. Also, I would try to generate the questions HTML, so that you're ready to generate quizzes with other sets of questions without having to re-type your html.
I'm trying to create a quizz-like app myself, currently, and would be glad to hear your feedback. A brief snipped of what I mean is on this fiddle: http://jsfiddle.net/xtofl/2SMPd/
Basically something like:
function verify(answers) {
jQuery.ajax("http://yoursite/verify.php?answers="+answers,
{ async: true,
complete: function(response, status){
// e.g.
alert(response.text);
}
};
};
This request would be sent when all answers are completed. I would try to create the questions on-the-fly using javascript and the DOM, something like:
function retrieveQuestions() {
//TODO: get them from a json-request like http://yourquizz/quizz1/questions
return [{ text: "what if Zoo went to Blohom in a Flurk?",
options: { a: "he frunts and vloghses",
b: "the Blohom doesn't snorf anymore" }
},
{ text: "how many this and that",
options: { a: "1", b: "2", c: "14" }
}
];
};
// retrieve and create the questions elements
var questions = retrieveQuestions();
questions.forEach(function(question, index){
jQuery("#questions").append(createQuestionElement(question));
});
// what does a question element look like:
function createQuestionElement(question){
var li=document.createElement("li");
var options = [];
Object.keys(question.options).forEach(function(key){
var o = document.createElement("div");
jQuery(o).on('click', function(){question.answer=jQuery(o).val();});
li.appendChild(o);
});
return li;
}
Your php backend verify.php script will check the arguments and return the result in json format, e.g.:
$correct = ($answers[ $_GET["question"] ] == $_GET["answer"]);
print("{ 'correct': '$correct' }");
(provided your answers are stored in an array $answers.
Yet another solution to the problem:
jsFiddle
We use event handlers, to check if an answer was clicked, then add the index of the answer to an array. When the last answer was submitted, we send the data to a php page, where you can process it using the $_POST array.
$('.question a').on('click', function (e) {
e.preventDefault();
var self = $(this);
var ans = self.parent().index() + 1;
answers.push(ans);
var hasNext = nextQuestion();
if (!hasNext) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"answers": answers
}
}).done(function (response) {
response = 'Stuff you output with PHP';
$('body').append('<p> Result: ' + response + '</p>');
});
}
});