Hi, I am writing a script that will allow a user to update the details of a recipe. I have got as far as getting all of the ingredients for the recipe and printing them out into editible form fields. I want the user to be abled to amend the "grammes" field and by doing so automatically updating the ounces field, which is disabled. I want this calculation to be done prior to the user submitting the form. If a user entered '500' into the grammes field for one of the ingredients the ounces field for this row should automatically change to '20' (500 x 0.04) when the user tabs away from. Please see my PHP code below for printing out the ingredients: Thanks in advance! echo "<table>"; while($get_ingredients->fetch()) { echo "<tr>"; echo "<td><input type = 'text' class = 'form-control' id = 'ingredient_name' name = 'ingredient_name' value = '$ingredient_name' ></td>"; echo "<td><input type = 'text' class = 'form-control' id = 'grammes' name = 'grammes' value = '$grammes' ></td>"; echo "<td><input type = 'text' class = 'form-control' id = 'ounces' name = 'ounces' disabled ></td>"; echo "<td><input type = 'text' class = 'form-control' id = 'other_amount' name = 'other_amount' value = '$other_amount' ></td>"; echo "<td><input type = 'text' class = 'form-control' id = 'other_unit' name = 'other_unit' value = '$other_unit' ></td>"; echo "</tr>"; } echo "</table>";
Don't set "ounces" text box disabled. You will not get disabled form field value via form submit. Make it read only. Replace disabled with readonly <input type = 'text' class = 'form-control' id = 'grammes' name = 'grammes' value = '$grammes' onBlur="set_ounces(this.value)"> <script> function set_ounces(grms){ document.form_name.ounces.value = 0.04 * parseInt(grms); // form_name: replace it with form name } </script> Code (markup): I have not tested the script but you can get basic idea how to do it
Mind you -- it's ok to calculate it client side to show it to the user, but you SHOULD NOT EVER trust a javascript calculation as a value in PHP. Sending that value server-side? Don't EVEN TRY. Hell, I wouldn't even make it an INPUT tag! ...well, unless it was made to go bi-directional on the conversion. Recalculate it server side so 1) it works when scripting isn't present, 2) people can't bullshit it. Remember the unwritten rule of JavaScript -- if you can't make the page function without JavaScript FIRST, you likely have no business adding scripting to it. Of course, if every tag inside a parent -- like say... TR -- is getting the same class -- like say... form-control, NONE of them need classes. Might also helped if you stopped using multiple echo to do the job of one, had a complete table structure, etc, etc... Though since you're got a while and a fetch, I'm wondering how you'd have it even work since you'd have the same ID more than once on the page. Also since it's a form (I'd assume) multiple elements with the same NAME would also be... problematic.