Outputting status as a number, code to change colour - javascript

I have added a 'status' column into my table and inputed numbers for them to be shown along with the id and content.
$res_array = array();
// fetch all the entires one by one
while($row=mysql_fetch_array($res)){
// put query result in php array
$array = array('id' => $row['id'],
'content' => $row['content'],
'status'=> $row['status']);
// add into the big array
$res_array[] = $array;
// update the list view
for (var i=0; i< res.length; i++){
$("<li/>", {"id": res[i].id, "text": res[i].content + res[i].status}).appendTo(todo.list);
// Extend the width if msg is too long
if(res[i].content.length >= 35){
$('#'+res[i].id).css("height","50px");
}
}
Above you can see how it is being displayed, i still cannot get teh if statement to change the colour of the content.
I want the content to change colour depending on the status number.
I dont know the code but i would imageine it would be an if statement for the status, but i need help
Thanks in advance.

If you have a finite and defined list of status codes then I would suggest simply adding them to a CSS class such as status5 and then define the colors/style for each of the status codes you return as a basic CSS rule
.status5 { color: red }

Related

Update status column on basis of multiple id in one table

i have subjects table with status column and parent_id column so from view page if i click on active button change the status to active/inactive..
So now if i click on subject active button it should change status of that child subjects too..
here is my code:
public function updateStatus(subject $subject)
{
$subject_id = $subject->id;
$subjects = Subject::where(['parent_id' => $subject_id])->get();
$subjects->status = !$subjects->status;
$subjects->save();
return redirect()->route('subject.index');
}
I am storing the main id in parent_id column.So if i change status of main id it should change status of related parent_id column status also. if it is 1 it should change to 0. if it is 0 it should change to 1.
Can anyone help me to solve this..TIA
If I understood correctly, first, you need to add parent data to your query:
$subjects = Subject::where('parent_id', $subject_id)->orWhere('id', $subject_id)->get();
Since this is a collection, you should create a loop to update each item. BTW, Laravel may have a built-in function for this, but I don't know.
foreach($subjects as $subject) {
$subject->update([
'status' => !$subject->status
]);
}
All you have to do is execute two queries, one for update status 0 where status is 1 :
Subject::where('parent_id', $subject_id)->where('status', 1)->update(['status' => 0]);
and other for change status 0 to 1 for the id you received
Subject::where('parent_id', $subject_id)->where('status', 0)->update(['status' => 1]);
So finally your code will be look like :
public function updateStatus(subject $subject)
{
$subject_id = $subject->id;
$subject = Subject::where('parent_id', $subject_id)->where('status', 1)->update(['status' => 0]);
$subject = Subject::where('parent_id', $subject_id)->where('status', 0)->update(['status' => 1]);
return redirect()->route('subject.index');
}

Laravel - JS [ajax] Var must be constant

i will be happy if someone know how to do this and why i m getting error , i would like to pass "var size" inside route() method inside forelse is it somehow passible ?
whot it do ?
based on radio box ( if size M and L are avaible there will be 2 radioboxes ), then if user click on add to card it gets Value of radio box for example ( 6 ) = L them pass it to ajax route
Error :
Use of undefined constant size - assumed 'size' (View: C:\xampp\htdocs\EcSc\resources\views\shop\home.blade.php)
JS :
<script>
var CartCount = {{ Session::has("cart") ? Session::get("cart")->totalQty : "0" }} ;
var size;
#forelse($products as $productsjs)
$("#product-{{$productsjs->id}}").click(function () {
var radios{{$productsjs->id}} = document.getElementsByName('radio-{{$productsjs->id}}');
for (var i = 0, length = radios{{$productsjs->id}}.length; i < length; i++) {
if (radios{{$productsjs->id}}[i].checked) {
// do whatever you want with the checked radio
size = radios{{$productsjs->id}}[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
$.ajax({
type: "get",
url: "{{route("product.addToCartAjax", $productsjs->id, size)}}", // insert product with specific size into session
success: function () {
CartCount++;
$("#shoppingCartCounter").html(CartCount);
console.log("Produkt bol pridani");
console.log("Velkost produktu je : " + size); // size contain value of checked radio box
}
})
});
#empty
#endforelse
</script>
You can't print the javascript variable in PHP. Think of {{ }} as <?php ?>. If you just insert it in there, it may look like <?php echo size; ?> which won't work, as obviously size will look like a constant here, which of course is undefined (your error).
Instead, you need to declare the variable in php. However, since you're doing this after run time, there's no way that you're going to be able to assign a PHP variable after the page has been rendered. So what are your alternatives?
1 - Construct the route manually: (recommended, easiest)
url: '/products/' + {{$productsjs->id}} + '/add-to-cart-ajax/' + size
2 - Use a client side route generator for Laravel, such as La Route (harder, but more dynamic and reusable)
laroute.route('product.{id}.addToCartAjax.{size}', {id: '{{$productsjs->id}}', size: size});
3 - Other generic solutions such as generating the route ahead of time and dynamically modifying it with javascript (ugly, non-portable)

PHP POST for HTML Select using another POST

This ain't something not working but just I'm confusing about how to do it, I want to fetch the values from my DB based on users' preferences that been chosen earlier.
These are the steps will be taken for my process:
User will select from images (will add HTML images then will whip it upon another selection)
Will continue till reaching last stage
Last stage will have 3 Select (dropdown menus) and 2 of them will change the content according to what user's chooses (like country and state dd)
My PHP:
else if ($_POST["data_key"]=="last")
{
$final_arr;
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$myquery="SELECT DISTINCT Layout.* FROM Layout,Products,Occasion, Cover, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.cover=$fetcher_cover;";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="size";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="size")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$myquery="SELECT DISTINCT Size.stitle FROM Layout,Products,Occasion, Size, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.size=Size.id";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="finishing")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$fetcher_finishing = $_POST["ftitle"];
$myquery="SELECT DISTINCT Finishing.ftitle FROM Layout,Products,Occasion, Size, Cover, finishing, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.cover=$fetcher_cover
AND Layout.finishing=$fetcher_finishing";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}}
My Engine JS (what I assign):
myItem.setId(jsonData[i].id);
myItem.setImg(jsonData[i].image);
myItem.setTitle(jsonData[i].title);
My Selects in JS (printing HTML):
myString +="<a>Sizes: </a><br><select id='sizesSelect' style=' width:200px'></select><br><br>";
myString +="<a>Cover: </a><br><select id='coverSelect' style=' width:200px'><br></select><br><br>";
myString +="<a>Finishing: </a><br><select id='finishingSelect' style=' width:200px'></select><br><br><br>";
Appending to Select in JS:
myString +="<script>$('#sizesSelect').append('<option val="+i+">"+this.getSize()+"</option>')</script>";
Now I need to know how can I post again to my PHP server to fetch the the values to other selects (refer for the img).
Select Size -> Update Covers -> Select Covers -> Update Finishing -> Select Finishing
Instead of using SQL to store and present previous user choices, you could keep the previous choices as $_POST data by re-adding the choises to the HTML Form as hidden input fields. Example: <input type="hidden" text="foo" name="<?=htmlspecialchars($_POST['foo'])?>">

For Loop in MVC 4 From JavaScript value

How can I make a repeater type in the page. In the page I have a quantity field:
<td>
#Html.DisplayNameFor(x => x.Quantity)
#Html.ValidationMessageFor(x => x.Quantity)
</td>
<td>
#Html.TextBoxFor(x => x.Quantity, new { #id = "txtQty" })
</td>
When I want to add the item, which there could be several of the same item, just different serial numbers, I need to pop open a div with repeated fields for entering serial numbers:
for (int I = 0; I < *****; I++)
{
<td>Serial Number:</td>
<td>#Html.TextboxFor(x=>x.Quantity, new { #id = "txtQty" + 1})
}
In the JS:
function AddItem() {
Qtys = parseINT($("#txtQty").val());
$("#divSerials").show();
}
How can I do this? Is there a better way?
Is this the way to do it? I try this but 'i' in the HTML model statement is not recognized.
if (parseInt($("#txtQuantity").val()) > 0) {
$("#divSerialNumbers").show();
var html = "<table>";
for (i = 1; i <= serialquantity; i++) {
html += "<tr><td>Serial Number:" + #Html.TextAreaFor(x => x.SerialNumber, new { id = "sns" + i }) + "</td></tr>";
}
html += "</table>";
$("#divSerialNumbers").html(html);
}
Razor code is parsed on the server before it is sent to the view. Javascript is client side code and is not executed until the browser receives the view. This line of code
#Html.TextAreaFor(x => x.SerialNumber, new { id = "sns" + i })
means that on the server you are trying to generate a textarea and set the id attribute to a value that includes a javascript variable which does not yet exist.
Its unclear even what the point of this would be. id attributes serve as selectors in javascript. Whats important is the name and value attributes when it comes to posting your data, and even if it could work, your generating duplicate name attributes which could not bind to you models collection property on post back.
For dynamically generating the html for collections, your name attributes need an indexer, for example <input type="text" name="[0].SerialNumber" />. Options for dynamically creating the html include using the BeginCollectionitem() helper, or a pure client side approach is shown in this answer
If all you are doing is post back an array of strings (the serial numbers) then you could use
var div = $("#divSerialNumbers"); // cache it
$('#Quantity').change(function() { // assumes you remove the pointless 'new { #id = "txtQty" }'
var quantity = parseInt($(this).val()); // use $(this) - don't traverse the DOM all over again
if (!isNan(quantity) && quantity > 0) { // must check for NAN
// note it does not seem necessary to use a table, as opposed to simply adding 4 inputs to the div, but
div.empty(); // clear existing contents
var table = $('</table>');
for (i = 1; i <= quantity; i++) {
var input = $('<input>').attr('name', 'SerialNumber');
var cell = $('</td>').append(input);
var row = $('</tr>').append(cell);
table.append(row);
}
div.append(table).show(); // add the table and display it
}
})
and your controller would need a parameter string[] SerialNumber, for example
public ActionResult Edit(string[] SerialNumber)

difficulty getting list of values from series of input elements inside table rows

I'm completely stumped. Granted, in java script i'm like that kid trying to jam a square peg into a round hole.
My high level objective: The admins want the ability to edit text surrounding some text boxes, as well as the ability to add and remove 'paragraph'. The reporters and users want the values that are in the textboxes to be used in comparisons, etc (which is the original functionality).
My Solution: This project uses a pretty messy value - attribute table (called an EAV?), which now has fields with associated fields and is self referencing. I decided to leverage this to minimize changes to the database, so the admin essentially creates a string, denotes the places a text box belongs using '{}', and assigns a name to the attribute into text boxes that appear directly below the paragraph.
My Problem: Textboxes generate fine, as soon as the admin stops typing the "{}" count is checked client side, and the correct number of textboxes are added/removed in rows below. However, when the "change" mode (and thereby save the new string) I also want to save the attribute names they selected. I can't seem to get the actual value out of the input. The java script below sends null to elementList. Closer inspection indicates that var fieldNames is getting two elements of "undefined" so it makes sense that I'm getting null. Its also apparent that Its hitting something, becuase the number aligns with there being two 'nameField' rows.
DOM (Hemed down to the essentials)
<tr data-editMode="TextMode" data-ordinal="0">
....
<td>
<a class="changeMode">
<tr class="nameField">
<td colspan='4'>
<input type="text" value="Testing">
<tr class="nameField">
....
Javascript
function getAssociatedTr(row) {
var associatedRows = [];
associatedRows.push(row);
row = row.next('tr');
var hasAnother = true;
while (hasAnother == true) {
if (row != null && row.hasClass("nameField")) {
associatedRows.push(row);
row = row.next('tr');
} else {
hasAnother = false;
}
}
return associatedRows;
}
$(".changeMode").live("click", function () {
var options = $(this).data("options");
var theRow = $(this).closest('tr');
var rows = getAssociatedTr(theRow);
var fieldNames = new Array();
rows.splice(0, 1);
for (var index = 0; index < rows.length; index++) {
{
fieldNames.push(rows[index].next('.nameField').val());
}
}
$(".modal-header", c.rowsModal).html("<h3>Changing edit mode" + options.table + "</h3>");
c.rowsModal.modal("show");
$.ajax({
type: "POST",
traditional: true,
data: { "Name": options.table, "Ordinal": options.row, "EditMode": options.editMode, "ElementNames": fieldNames },
url: "/contracts/changeeditmode/" + c.id.val(),
success: function (data) {
theRow.replaceWith(data);
$.validator.unobtrusive.parse("#supplementForm");
c.rowsModal.modal("hide");
for (j = rows.length - 1 ; j >= 0; j--) {
rows[j].remove();
}
}
});
});
Server side
public ActionResult ChangeEditMode(long id, AddTrackedRowViewModel model,
string editMode, List<string> elementNames)
{
}
As a side note, I'm open to constructive criticism on the JavaScript.
EDIT
I have updated the line to
fieldNames.push(rows[index].nextAll('input').first().val());
But still getting undefined.
SOLUTION
fieldNames.push(rows[index].find("input[type=text]").val());
In this line:
fieldNames.push(rows[index].next('.nameField').val());
you are using the selector ".nameField", but this get a "tr" element, if you want the textbox you need this:
fieldNames.push(rows[index].next('.valid').val());
or using other selector that give you the textbox.

Categories