Javascript If Else events - javascript-events

I have the following script which functions perfect.
function showResult(questionId) {
if(answers[questionId] == useranswers[questionId]) {
document.getElementById('result_' + questionId).innerHTML = '<img src="correct.gif" style="border:0" alt="Correct!" />';
} else {
document.getElementById('result_' + questionId).innerHTML = '<img src="incorrect.gif" style="border:0" alt="Incorrect!" />';
}
}
I would like the ELSE condition to perform a 2nd action- show the correct answer when the user has chosen the wrong answer, eg. like making the correct answer appear in Green. This is for a multiple choice question that has 4 choices with only 1 correct answer.
All help appreciated. Many thanks.

function name(){
if(this == that){
then;
}else if(this2 == that2){
then2;
}
}
You can always nest IF statements or you can duplicate ELSE IF calls like above to infinity...

Related

If condition in Kendo UI grid template

field: 'Status' ,
width: '70px' ,
template: "#if(Status == 'On Request') {#<div class='redAndBold'>#:Status</div>#}#"
I have a kendo UI grid where the "Status" is being filled in from the javascript file. The Status in the model can be "On Request", and what I want is: if it is "On Request", add a class to it, "redAndBold". The syntax in this particular example gives a "user is not defined" error.
Could anyone give me some pointers on how to correctly do this?
The kendo.templates depend on #=fieldName# or #:fieldName#. In the current case, there is a missing closing "#" after 'Status'. The templates are evaluated with the value of the field when bound to a data item during initialization. For executing JavaScript logic use only "#JS logic goes here#". Further information can be found here Kendo UI templates.
To avoid confusion of the template syntax, plain JavaScript function can be used instead:
template: "#=templateFunc(data)#"
// JS hander
function templateFunc(dataItem){
if(dataItem.Status== 'On Request') {
return "<div class='redAndBold'>"+dataItem.Status+"</div>";
} else{
return dataItem.Status;
}
}
I think you are missing a # after Status. When you inject the value of a variable it needs a # before and after. If you split the template code over several lines whilst you write it, it can be easier to get it right.
#if(Status == 'On Request') {#
<div class='redAndBold'>
#:Status#
</div>
#}#
A good check is to count the number of # symbols in your template. It should always be an even number.
As many people pointed out, you're missing a pound sign. I would like to point out that you can set the template as a function that returns a string. I generally do this because there are nuances with the string template such as escaping pound signs among other things:
field: 'Status',
width: '70px',
template: function(dataItem) {
var div = $('<div />');
if (dataItem.Status === 'On Request') {
div.addClass('redAndBold');
}
return div.prop('outerHTML');
}
Just use function for a template :
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

Load in div based on choice in selectbox

I have an box in Page1 with some different alternatives and below this a div where I want to load in content (different divs) from an external page (Page2) based on choosen alternative.
Page1
<select id="choose_alternative">
<option> Books </option>
<option> Paper </option>
</select>
Page2
<div id="Book_div">Content</div>
<div id="Paper_div">Content</div>
I found THIS POST and tried figure out how to use the code and ended up with this:
$("#choose_alternative").change(function(){
$("#show_alternative").load( $(Page2.html #Book_div).val() );
$("#show_alternative").load( $(Page2.html #Paper_div).val() );
});
Does anybody know what I have done wrong?
Thanks.
If I understand your question right, what you want to do is according to the selection load the div. check the code below.
$("#choose_alternative").change(function(){
var choose_alternative = $("#choose_alternative option:selected").text();
if(choose_alternative == 'Books'){
$("#show_alternative").load('Page2.html #Book_div');
}
else if(choose_alternative == 'Paper'){
$("#show_alternative").load('Page2.html #Paper_div');
}
});
else you can just load the content right away
$("#choose_alternative").change(function(){
$("#show_alternative").load("Page2.html #Book_div");
$("#show_alternative").load("Page2.html #Paper_div");
});
Read more
Here is the relevant part of the documentation:
http://api.jquery.com/load/#loading-page-fragments
It says to do it like this:
$("#choose_alternative").change(function(){
$("#show_alternative").load("Page2.html #Book_div");
$("#show_alternative").load("Page2.html #Paper_div");
});
Ok I dont get it to work so something is wrong. Its strange becuse there is other similar scripts on the same page that works great.
$(document).ready(function (){
$('#choose_alternative').change(function(){
$show_alternative = $('#show_alternative');
var selectedElement = $('#choose_alternative :selected');
switch($(selectedElement).val())
{
case " Books ":
$show_alternative.load('Page2.html #Book_div');
break;
case " Paper ":
$show_alternative.load('Page2.html #Paper_div');
break;
default:
$show_alternative.html('No option selected.');
break;
}
}
}
Never forget the $(document).ready( function(){...}) part; it is what renders your code so it can be triggered.

codeigniter - conditional if else statement using a href

I know this is a weird question, but let me explain more. I use codeigniter as framework to make my site. I have some code that contain if else condition in view and want to use that as a href so it becomes like a button that changes based on whether the condition has been met or not.
here is the code:
<?php if($this->tank_auth->is_logged_in())
{ echo anchor("auth/logout/","Logout");
} else {
echo anchor("auth/login/","Login");
?>
I was looking around in the net, but couldn't find a similar case where if else statement being used.
any idea how to achieve that?
Thanks
That should work fine, as long as tank_auth is loaded and you have a closing bracket after your else condition:
<?php
if($this->tank_auth->is_logged_in()) {
echo anchor("auth/logout/","Logout");
} else {
echo anchor("auth/login/","Login");
}
?>
You might also consider moving your check for the user's login to your controller, however, so as to keep tank_auth out of your views:
// ...end of controller function
$data['logged_in'] = $this->tank_auth->is_logged_in();
$this->load->view('my_view', $data);
}
In this case, you would then run your conditional on $logged_in in your view.

Prototype observers attached to a class firing multiple times

Thanks in advance for your help guys.
I consider myself pretty well-versed in jQuery but as I was helping my sister with her Prototype homework, this frustrated the crap out of me. She couldn't solve it in time so that's moot but for my sanity's sake, I hope you can tell me what's going on.
We were simply creating a netflix-style queue with add, reorder and delete through AJAX. The items were in a UL and had a delete link inside each LI with unique IDs to be used for deletion. Please don't fixate on why we were using text files to save data, etc. - her professor made that impractical choice a requirement, along with a few others...
JS:
function softRefresh() {
$$('.delete').invoke('observe','click',function() { taskDelete(this.id); });
Sortable.create("taskList", { onUpdate: function(list){ saveOrder(list); } });
}
function taskDelete(a) {
var tempArr = a.split('-');
var keyToDelete = tempArr[1];
var output;
var ajaxRequest = new Ajax.Request("todolist.php",
{
method: "post",
parameters: {
action: 'delete',
id: keyToDelete
},
onSuccess: function(response) {
$('taskList').update(response.responseText);
softRefresh();
}
});
}
PHP for the 'delete' action:
$jsonOutput = file_get_contents($myFile);
$fetchedArr = json_decode($jsonOutput);
$newArr = array();
foreach($fetchedArr as $key => $task) {
if(($key != $_POST['id'])) {
array_push($newArr, $task);
}
}
$jsonOutput = json_encode($newArr);
file_put_contents($myFile, $jsonOutput);
$output = '';
foreach($newArr as $key => $task) {
$output .= '<li id="list_'.$key.'">';
$output .= $task;
$output .= 'X';
$output .= '</li>';
}
echo $output;
The problem was that if I deleted, say, the 2nd item, all the following items would delete as well. Through firebug console I found out that this is because when you click any link of that class ('delete') all the following listeners fire, and keeps deleting the 2nd item off the new list. Can you tell me why and how I can set it so it only fires off the link you click? It drove me nuts all day. I'm used to having .click() on jQuery... much hatred for Prototype at the moment.
Thanks again!
JS:
You shouldn't need the softRefresh if you set the events well. Likewise, the <ul> element is never disposed nor replaced so only one Sortable should be necessary, there is no need to remake that each time.
Event.on('taskList', 'click', '.delete', taskDelete);
Sortable.create("taskList", { onUpdate: saveOrder });
function taskDelete(event, element) {
var id = element.id;
var tempArr = id.split('-');
var keyToDelete = tempArr[1];
new Ajax.Updater({success: 'taskList'}, "todolist.php",
{parameters: {
action: 'delete',
id: keyToDelete
}}
);
}
(Ajax objects in prototype are already POSTs so that doesn't need to be specified. Use of an Updater is neater too. There is little point in wrapping a function call in an anonymous function, it may be the jQuery way but it isn't adding any functionality, javascript functions are objects so use them as such.)
PHP:
I felt $newArr was a waste of a loop and some memory so here is a shorter way.
$jsonOutput = file_get_contents($myFile);
$fetchedArr = json_decode($jsonOutput);
unset($fetchArr[$_POST['id']]);
// Keys are preserved here, if you need to reorder use:
// $fetchedArr = array_values($fetchArr);
$jsonOutput = json_encode($fetchedArr);
file_put_contents($myFile, $jsonOutput);
foreach($fetchedArr as $key => $task) {
echo '<li id="list_'.$key.'">';
echo $task;
echo 'X';
echo '</li>';
}

aggregate form elements into object ?

i am trying to aggregate form elements into object and then send it via ajax here is the code that i start using but i cant figure out how to do the rest
$('.jcart').live('submit', function() {
});
Update 1:
html form
http://pasite.org/code/572
Update 2:
I have successfully submit the form using ajax but it still refreshes the page after submiting
this what i did
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
jQuery has a method called .serialize() that can take all the form elements and put them into an array for just what you are trying to do. Without seeing your html, we really can't tell you much more though.
http://api.jquery.com/serialize/
Something like this might work:
$('.jcart').submit(function() {
$.ajax({
url : form.php,
type : "POST",
data : $(this).serialize(),
});
});
Obviously it would need a little more for full functionality, but that should get you started.
Depending on how many of the values you need (and whether you have things like radio buttons) you can start with the :input selector to grab the elements. Assuming .jcart is your form or container, something like this:
var data = {};
$('.jcart').find(':input').each(function (i, field) {
if ($(field).is('input:checkbox') {
if (field.checked) {
data[field.name] = true;
} else {
data[field.name] = false;
}
} else {
data[field.name] = $(field).val();
}
});
That should get you started.

Resources