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();
});
}
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
i'm wrote some todo list app, to understand how to be more expert.
what i'm try to understand:
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object.
(i attached my code here).
my questions:
1) in my code i wrote one way to fix it, by clone object every time.
it good practice ? if no how you recommend me to fix it?
2) because i do not want my code only work, i want to be more expert.
if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
thanks for help :)
link to plunker: https://plnkr.co/edit/CA99iiydbD4TWaGtJZZf?p=preview
code:
HTML
<html ng-app="todos">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="main">
<ul>
<li ng-repeat="task in todosBL.tasks" ng-click="editMode.edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="task">
<input type="button" value="add task" ng-click="add(task)">
<!--//for edit-->
<div>
<input type="text" ng-model="editMode.task.content">
<input type="button" value="save task" ng-click="editMode.save(editMode.task)">
</div>
</div>
</body>
</html>
SCRIPT:
(function() {
var Task = (function() {
var counter = 0;
return function(content, isDone) {
this.id = counter++;
this.content = content;
this.isDone = isDone || false;
}
}());
var app = angular.module('todos',[])
.service('todosBL', function() {
this.tasks = [];
this.add = function(content) {
this.tasks.push(new Task(content));
}
this.update = function(editedTask) {
var i = this.tasks.findIndex(function(task){
return task.id === editedTask.id
});
this.tasks[i] = editedTask;
}
})
.controller('main', function($scope, todosBL) {
$scope.todosBL = todosBL;
$scope.add = function(task) {
todosBL.add(task);
$scope.task = null;
}
$scope.editMode = {
task: {},
edit: function(task) {
this.task = task;
//BECAUSE I PASS TASK BY REFERNCE WHEN USER EDIT TASK IT CHANGE TASK DIRECTLY ,
// IF I CLONE OBJECT EVERY TIME, IT FIX BY REFERENCE PROBLEM.
// MY QUESTION IF HAVE OTHER WAY TO SLOVE THIS. MABY OTHER WAY TO THINK ABOUT APP LIKE THIS.
// for(key in task) {
// this.task[key] = task[key];
// }
},
save: function(task) {
todosBL.update(task);
this.task = {};
}
};
});
}());
I think that your controller is over complicated. The service should implement some BL like data verification and posting it to the server and/or local storage but not searching for index, it does silly things now!
In order to satisfy all your requirements one just needs a controller:
app.controller('MainCtrl', function($scope) {
$scope.tasks = [];
$scope.add = function(content){
$scope.tasks.push(new Task(content));
$scope.content = null;
}
$scope.edit = function(task){
$scope.currentlyEditing = task;
$scope.editText = task.content;
}
$scope.save= function(){
$scope.currentlyEditing.content = $scope.editText;
$scope.editText = null;
$scope.currentlyEditing = null;
mySuperSeriousService.postToServer.then(result=> {
alert('Success');
})
}
});
and template like this:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="task in tasks" ng-click="edit(task)">{{ task.content}}</li>
</ul>
<input type="text" ng-model="content">
<button ng-click="add(content)">Add Task</button>
<!--//for edit-->
<div>
<input type="text" ng-model="editText" ng-disabled="!currentlyEditing">
<button ng-click="save()">Save</button>
</div>
</body>
So it's 2 times shorter. Here's the plunker (https://plnkr.co/edit/nN8kd5ErSDsBu6Exm1YO)
my problem is when user click on task to edit, because it passed by reference so if user edit task, it will change directly the task object. (i attached my code here).
For solving this problem, you should make a copy of your model and change it (in edit function): this.task = angular.copy(task);
in my code i wrote one way to fix it, by clone object every time. it good practice ? if no how you recommend me to fix it?
As I said, making copy is much more logical !
because i do not want my code only work, i want to be more expert. if you think my thinking and planning of this code is bad? how you write this app? ( i talk here only about functional, add, edit, list of task)
1) I don't know why you are using an array of objects ? your tasks are just strings ! so it can be better if you use an array of strings. then you won't have the struggle with sth like editMode.task.content, you just use editMode.task !
2) Don't work with ids . cause when you add the 'Deleting Task' feature, you'll got problems ...
3) What does Task() function do ? ( In this case, you don't need sth like this)
4) ...
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
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>');
});
}
});