document.getElementById is NULL error - php

I have a function that listens for onkeyup event, that onkeyup checks to see if a box has a value and if not blank is supposed pull the value of an elementID which is a phone number called from another page. It takes that value and inserts it in to a snippet of html that gets sent to another elementID. the folowing code is the function and the associated code.
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
document.getElementById("cancelphonelistLabel").value = cancelPhone; <--gives the is null error
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label>";
" </span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
all the data is pulled together in a single page when loaded but is written in separate page using smarty templates. I keep getting the entitled error and have tried a number of different things to fix it but im stumped any help is greatly appreciated.
here is a jfiddle http://jsfiddle.net/rn5HH/

I think you are trying to access that id before it's created.
Also .value is only for inputs. It looks like you are creating a label, so you'd use innerHTML instead.
Something like this:
<script language="javascript">
function monthlycheck() {
var mnthchk = document.getElementById("mdamountBox");
var cancelPhone = document.getElementById("cancelphoneLabel");
if(mnthchk.value!=""){
var newHTML = "<span style='color:#24D330'> Your Monthly pledge in the amount of $__ is valid and will be deducted this time every month<br> untill you notify us of its cancellation by calling <label id='cancelphonelistLabel'> </label></span>";
document.getElementById("mnthlychkdiscoLabel").innerHTML = newHTML;
document.getElementById("cancelphonelistLabel").innerHTML = cancelPhone; //<--gives the is null error
}
}
</script>
<label id="mnthlychkdiscoLabel"> </label> <---this is where the final data is to be displayed
<label id="cancelphoneLabel">1-800-555-1111</label> <--- this is the phone number pulled from another page,
I'm not 100% what you are trying to do, so i just tried to make it work. There are many things you could probably simplify in this. It would help if you could create a jsfiddle to show it more clearly.
Edit:
Fixed the fiddle so it works and shows the phone number:
updated fiddle
Is that what it's supposed to do?

Related

How to get current selected value in PHP

I am new to PHP development. I wan to echo the selected value in a container and show it as and 'echo'. In the code <div id="selected_mters_container"></div> have the serial number. A jquery call is made and the selected meter serial number is displayed like shown below
Now i want to save this serial number in a variable. Below is the JQuery
jQuery('#the-mter-id').on('typeahead:selected', function (e, datum) {
$('#selected_mters_container').html('');
$('#metersinventorystore-store_id').val('');
$('#metersinventorystore-historic').val('');
var html = '<div class="selcted-meters"><input type="hidden" name="selected_meters[]" value="'+datum.id+'" />'+datum.meter_serial+'<a onclick="$(this).closest(\'.selcted-meters\').remove()">X</a></div>';
$('#selected_mters_container').append(html);
$('#metersinventorystore-store_id').val(datum.store_id);
$('#the-mter-id').typeahead('val','');
$('#metersinventorystore-historic').val(datum.historic);
});
As a newbie I don't know how to do it
Any help would be highly appreciated
Try :
var theVALUE = $('#selected_mters_container').html();
alert(theVALUE);

JQuery var to form POST for PHP

To start off, sorry if this is a duplicate, or explained already. I've read a minimum of 15 other topics that I assumed are similar to mine, yet I haven't had any success in getting it to work.
I currently have a form that is action="submit.php". The form is an order form (see Jfiddle link at bottom of post). Inside submit.php I'm making an array of all $_POST values. That works great. Now the problem:
On the forum page (where user inputs), I have the following JQuery script that calculates totals. There are 3 types of totals (all this is clear in the JFiddle). The 3rd total, called "overallTotal", takes the sum of all "grandTotal"s and as of now, puts in #overallTotal ID. I need that number to be included in the form submission (i.e., so it is accessible by $_POST).
Thanks in advance, and sorry again if this is repetitive.
JSFiddle: http://jsfiddle.net/rc694dzL/
function oninput(e) {
// process this row first
var row = $(e.target).closest("tr");
// explicitly cast to a number
var quantity = +$(e.target).val();
var price = +row.find(".val1").text();
var output = row.find(".multTotal");
var total = price * quantity;
output.text(total);
// now calculate total
var subtotal = 0;
var table = $(e.delegateTarget);
table.find(".multTotal").each(function () {
subtotal += (+$(this).text());
});
table.find(".grandTotal").text(subtotal);
// now calculate overall total
var overallTotal = 0;
$(document).find(".grandTotal").each(function () {
overallTotal += (+$(this).text());
});
$('#overallTotal').text(overallTotal);
Add a hidden input in your form like this
<input type="hidden" name="overallTotal" id="overallTotalInput">
and set the value from javascript like this
$('#overallTotalInput').val(overallTotal);
Now when submitting the form, the value will be stored into $_POST['overallTotal']
Add some hidden fields in the form, and then populate the values with jquery.
Edit: tweaking your Fiddle now with an example: http://jsfiddle.net/dozecnp6/1/
1) Added the hidden input in the form:
<input type="hidden" name="OverallTotal" id="overallTotalField">
2) Added a bit to your oninput() function:
$('#overallTotalField').val(overallTotal);
in this fiddle i can use type="text" you can change it to type="hidden"
check this
fiddle

jQuery/Javascript calculator that auto-updates realtime (guessing AJAX)

I'm looking to create a pretty simple calculator, but I need it to update on each keystroke. I cannot seem to find anything in that specific category. Can anyone point me to the right direction?
I'm looking for something like A*1.325 + B*3.76 where B is a drop down menu and A is the text field that people will be filling out. Every time the drop down is changed or a keystroke is registered in the text box.
I will also try to do some RegEx to only allow numbers or decimal points!
Thank you guys very much!!!
PS. Will be using PHP/HTML to create the form.
Step 1:
Do the jQuery tutorials. fun fun fun :D :D :D
http://docs.jquery.com/Tutorials
Step 2:
Now that you understand jQuery, notice that jQuery supports a bunch of event handlers. For instance, you can assign a click event to something that resembles an item in a dropdown menu:
$("itemInMyDropDownMenu").click(function(e) {
doSomeCalculation(parseFloat(this.val()));
}
Step 3:
Chose the right event handlers to use. click (for the dropdown menu) and keyup (for the text field) sound hopeful.
Step 4:
Keep tinkering. You don't need PHP at all.
The first question. If you need just simple calculator, why would you need AJAX? AJAX can send requests to web pages and scripts and get the XML, JSON, html or simple text responses.
If you still need AJAX, read http://www.w3schools.com/ajax/default.asp
Realtime updates:
Set the id of elements you are going to work with.
Create the appropriate handler, which is called any time the field is changed.
<input type="text" id="field" value="" onChange="javascript: setA(this)"/>
function setA(obj){
var a = 0 ;
if (obj.value)
a = obj.value ;
//call any function to calculate anything and send a.
}
If you want to display something, here id comes to be handy.
<div id="result"></div>
document.getElementById("result").innerHTML = 345 ; //just set to what you need
You can fully utilize javascript for building simple calculator without submitting the form, as it can work in real time.
Hope it helps :)
While I waiting to hear back I did a little more research and found some code that I think will work for what I was looking for. I was overthinking the whole thing!!
<html>
<head>
</head>
<body>
<script>
function doMath() {
var totalparts = parseInt(document.getElementById('parts_input').value);
var labor = parseInt(document.getElementById('labor_input').value);
var misc = parseInt(document.getElementById('misc_input').value);
var subtotal = totalparts + labor + misc;
var tax = subtotal * .13;
var total = subtotal + tax;
document.getElementById('subtotal_input').value = subtotal;
document.getElementById('tax_input').value = tax;
document.getElementById('total_input').value = total;
}
</script>
<div>Total Parts: <input type="text" id="parts_input" value="1" readonly="true" /></div>
<div>Labor: <input type="text" id="labor_input" onBlur="doMath();" /></div>
<div>Misc: <input type="text" id="misc_input" onBlur="doMath();" /></div>
<div>Sub Total: <input type="text" id="subtotal_input" readonly="true" /></div>
<div>Tax: <input type="text" id="tax_input" readonly="true" /></div>
<div>Total: <input type="text" id="total_input" readonly="true" /></div>
</body>
</html>
You don't need to use, and shouldn't use, AJAX for this. Instead, you should do something like this:
$("#textfieldID, #dropDownMenuID").change(function() {
var aVal = $("#textFieldID").val() == "" ? 0 : parseFloat($("#textFieldID").val());
var bVal = $("#dropDownMenuID").val() == "" ? 0 : parseFloat($("#dropDownMenuID").val());
$("#answerID").text((aVal*1.325 + bVal*3.76).toString());
});
Have you tried onchange="calculator()"?

php comparing value from database with one in a textbox

i have a multiple amount of text fields, the amount of text fields is due to how much data is in a database. The input for both are integers, all i want is when the values are inputted into the text fields it throws an error if the inputted data is larger than the value in the data base
for example
in a markscheme
the data inputted into the textbox is the mark given to the student and the data in the database is the maxmark for that particular question, so therefore it cannot exceed that value
so in effect i want to compare the values and if the text input value is larger than that of the one in the database it throws and error :)
If it's OK for you to rely on your users having javascript enabled, I would say the easiest is to verify the data on the client side.
You could do something like this:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="text" value="5" name="grade[123]" data-max="10" />
<script type="text/javascript">
$(function() {
$('input[type="text"]').blur(function(e) {
var $this = $(this);
var max = parseInt($this.data('max'), 10);
if (parseInt($this.val(), 10) > max) {
var name = $this.attr('name');
console.error('Value ' + $this.val() + ' in field "' + name + '" exceed its maximum value of ' + max);
$this.focus();
}
})
});
</script>
</body>
</html>
Or you could replace all this logic with simple HTML5 number fields:
<input type="number" value="5" name="grade[123]" min="0" max="10" />
Obviously, one should never trust their users. You should always double-check the data on the server side and notify users about the possible errors.
This is something you could do:
<?php
if (!empty($_POST)) {
// ...
// fetch max values from the database in the form of
// array(
// id => [max],
// );
$maxValues = array( /* ... */ );
// prepare some error array if you want to show errors next to individual fields
$errors = array();
// ...and then loop through the posted array
foreach ($_POST['grades'] as $id => $value) {
// make sure the submitted value is an integer
if (!ctype_digit($value) && !is_int($value)) {
$errors[$id] = 'Invalid value';
continue;
}
if ((int) $value > (int) $maxValues[$id]) {
$errors[$id] = 'Value cannot be more than ' . $maxValues[$id];
}
}
// assign errors to the view or do whatever is required in your script
// ...
}
It shouldn't be difficult to understand what I was doing there. Basically, have one reference array and the data array to verify against (note: your HMTL field names must have the square brackets in them to act as arrays). And then just loop through the submitted data and verify against the reference array.
Just like Ryan Kempt said, there are lots of ways you could do it and without a specific example of your data structure or how you want the errors/exceptions to be presented to the user, it's quite difficult to write you an exact code.
Nevertheless, have a look at our suggestions and start from there. And best of luck!
Lots of ways to tackle this but pretty much with everything you can use a javascript solution for client-side checking and PHP for server-side... for front-end you could query the DB and output the information in hidden inputs and then compare the value of the textbox to the value of the matching hidden div using a javascript solution.
When the textbox loses focus you could use AJAX and query what's in the textbox against your database.
When the user submits the form finally you should also then verify the numbers again against the daabase using PHP.
So... would need more information but the above steps are what you're going to want to do - how you do them is up to you and if you need specific help after trying the above methods and running into issues, we'd love to help you more.
Happy coding and best of luck!

PHP $_POST value being lost when using JS .insertAfter()

I have the following code, which should adds a field to a form if the user selects 'Other' from a dropdown. However, using this code seems to overwrite the value of the dropdown, so that when the form is posted $_POST['enquiry_source'] is empty.
I've narrowed it down to this line that is causeing me the problem buy adding the field on any change in the dropdown, not just if 'Other' is selected -
$(field_to_append).insertAfter('#form-field-enquiry_source');
I've also tried $('#form-field-enquiry_source').after(field_to_append);, but the result was the same.
$(function(){
/** Looks for changes to the enquiry source dropdown */
$('#form-field-select-enquiry_source').live('change', function(){
/** Check the enquiry source */
var enquiry_source = $('select[name="enquiry_source"]').val();
/**
* Adds another field to the enquires form when the user selects 'Other' form the enquiry source dropdown
*/
if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form
var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
'<label>Other<span class="required"></span></label>'+
'<input name="enquiry_source" id="form-field-input-enquiry_source_other" />'+
'</div>';
$(field_to_append).insertAfter('#form-field-enquiry_source');
} else {
$('#form-field-enquiry_source_other').remove();
}
});
});
Any ideas what is causing this problem?
If you have a select with name = enquiry_source and then you ad an input with the same name only one element is posted to the server, in your case the input field (only the latter element is posted) so you should give the field a different name
var field_to_append = '<div id="form-field-enquiry_source_other" class="form-field float-left">'+
'<label>Other<span class="required"></span></label>'+
'<input name="enquiry_source_other" id="form-field-input-enquiry_source_other" />'+
'</div>';
Are you inserting inside? sounds like you are generating a html code like
<form>something</form><input name=enquiry_source>
Maybe what you want is $('#form-field-enquiry_source').append($(field_to_append));
I don't know what is "#form-field-enquiry_source". Is a form?
I know this may seem a bit off topic (but kind of is not). You could change your approach by having a hidden div with those contents already within it, then your problem comes down to having the drop down show/hide depending on the field.
The nice part about this is upon javascript minification that long strings cannot be minified, you will save a lot more space by doing it this way.
if(enquiry_source === 'other'){ // The user has selected other as the enquiry source, so lock the form
$("#enquiry_source_other").show();
} else {
$("#enquiry_source_other").hide();
}
I feel like this approach is a bit simplier

Categories