return values from Jquery function - javascript

I am a complete novice in jQuery and javascript, so if this sounds very silly or very simple thing to do please help me out with your expertise
$(document).ready(function(){
$('#add_button').click(function(){
var vol = $('input#cv').val();
var col = $('input#cc').val();
var comment = $('input#co').val();
var sample = $('#cv').attr('class');
var url = $('input#cv').attr('title');
if( (vol && col && comment) == ''){
alert('No data to update');
}else{
url = url.concat('volupdate=',vol,'&concupdate=',col,'&commupdate=',comment,'&sample=',sample);
alert(sample + " " + vol + " " + col +" "+ comment +" " + url);
}
});
});
html :
my $correct_vol = qq{<input type="text" name="cv" id="cv" size="6" class="$sample_name" title="/here/is/where/you/are">};
my $correct_conc = qq{<input type="text" name="cc" id="cc" size="6" class="$sample_name" title="/here/is/where/you/are">};
my $comments = qq{<input type="text" name="co" id="co" size="10" class="$sample_name" title="/here/is/where/you/are">};
my $update = q{<input type="submit" value="Update" id="add_button" class="add_now">};
These forms the last four columns in a big table. My question is: How should I return the url in jquery function to my perl?
if I use return url what should I expect ? And how should I handle the values passed from the url in my script? Thanks for your suggestions.

Your javascript code won't connect with your perl code by itself. The connections to perl will happen as it processes the form elements. So your values need to be passed via POST or GET, the same way they would be passed if you were doing this in an HTML + perl only solution.
What you can do in your javascript is to set the value of the form input that you need to pass. That would be accomplished via something like $("#inputElementID").val(url); (assuming that you give the input element an id of inputElementID in the html where you create it.
You could also submit the form through javascript, if it made sense to do so.
As to using return url, that will only end up returning the value of url to the javascript function that calls it (which, in this case, doesn't really exist since this is a document.ready() execution.

Related

Only a specific variable works for my ajax code

I am so confused. I have a form and for now, I send a value into my javascript function. It works with a specific name "bookDate" but whenever I decide to change the name, it gives me an index unidentified error.
HTML FILE:
<input name="submit" type="button" onClick="postBooking('postbooking.php','targetDiv', pickUpDate.value, pickUpTime.value) " value="Book a Cab!">
Javascript:
function postBooking(dataSource, divID, bookingDate, bookingTime) {
if (xhr) {
var place = document.getElementById(divID);
var url = dataSource + "?bookDate=" + bookingDate + "&bookTime=" + bookingTime;
xhr.open("GET", url, true);
PHP:
$pickUpDate = $_GET["bookDate"];
$pickUpTime = $_GET["bookTime"];
echo $pickUpDate." ".$pickUpTime;
In the javascript, when I change "bookDate" into another name (I change the php GET as well to match) it starts to give an index unidentified message when I click my button. It works fine the way it is so I'm so confused why only that name works.

Passing HTML parameters to php page

I am attempting to pass the parameters of the current html page to the php page using a form. So far I have the following function inside my header in the html
<script>
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
</script>
and then in the form I have the following
<input type="hidden" name="amtpaid" id="amtpaid" value="getURLParameter('amt')" />
<input type="hidden" name="status" id="sts" value="getURLParameter('st')" />
this is assuming a url such like
www.somehost.com/page/?amt=5&sts=CONFIRMED
however all that the php says is posted is the following (this is aa dump of all post data)
Array ( [on1] => Steam 32 - ID (STEAM_0:X:XXXX) [os1] => hj [amtpaid] => getURLParameter('amt'); [status] => getURLParameter('st'); )
anyhelp??
You're passing the literal string "getUrlParameter('amt')" as the value of the fields you are posting. You can't populate the "value" in this way. What you need to do is populate the values from javascript. Like this:
document.getElementById("amtpaid").value = getUrlParameter('amt');
document.getElementById("sts").value = getUrlParameter('st');
This would need to be placed somewhere in a script tag in the page where it would be executed at a time that makes sense for your application, after those two hidden fields are loaded.
Put this script under your form or input fields:
var amount = getURLParameter('amt');
var stat = getURLParameter('sts');
document.getElementById("amtpaid").value = amount;
document.getElementById("sts").value = stat;

Selecting and changing an appended HTML input tag in Jquery

I have an issue I cannot solve through research/Google. I successfully appended the following input boxes to my HTML/JQuery project. They all appear as intended on the web page.
for (i = 0; i < max; i++) {
var id = myUniqueIDs[i];
$("#targetedDiv").append(myUniqueIDs[i] + ': <input id = "' + id + '" type = "text" class = "findOutputs" readonly/>');
}
Later on in my code, after some user interaction, I try to write some info into the input boxes. They cannot be written into by the user (they are readonly). I know I can write into a read only input box via Jquery because it is done elsewhere in my project. However it just isn't working.
for (i = 0; i < max; i++) {
var y = getY(); // the returned variable is confirmed correct via debugging
var id = myUniqueIDs[i]; // again, confirmed correct
$('#' + id).val(y); // does not work
}
When I put var test = $("#targetedDiv").html(); in my code it I can see that test is
uniqueID1: <input id="uniqueID1" class="findOutputs" readonly="" type="text">
uniqueID2: <input id="uniqueID2" class="findOutputs" readonly="" type="text">
uniqueID3: <input id="uniqueID3" class="findOutputs" readonly="" type="text">
So I honestly have no idea what the issue is. Is there something illegal with $('#' + id).val(y);?
Can you not select an appended tag in Jquery? Can someone point out what I am missing here?
The issue is definitely with the selection because I tried var test = $("#targetedDiv").html(); AFTER the part where I change the value and there is no difference on the variable test as when it was done before the second loop, so $('#' + id).val(y); (or other suggestions in answers) is having no effect.
Musa answered the question in the comments.
"If the ids contain special characters you'll have to escape them."
My (real) IDs contained a space.

Updated HTML from JavaScript variable

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?
Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle
I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!
i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx
I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

JavaScript - How to assign user input value to variable inside script

Using widget script--http://socialmention.com/tools/-- from Social Mention. Tried to modify by adding input box to allow user to change social media topic (var smSearchPhrase). I created a function [smSearch()] to retrieve user data (smTopic), assign it to a new variable (var newTopic) and then assign that value to var smSearchPhrase. The assignment does not work.
The function appears to work based on values observed via alerts, however, I cannot figure out how to assign the value from var newTopic to var smSearchPhrase inside the script. I experimented by placing script inside the function, but that didn't work either. Any assistance is appreciated.
If I failed to include all necessary information, please advise. Thanks for any assistance.
HTML:
<form>
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button onclick="smSearch()">Submit</button>
<input type="reset">
</form>
Function: (includes alerts to check values)
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
Script: var smSearchPhrase in original has value assigned, e.g. var smSearchPhrase = 'social mention';
<script type="text/javascript">
// search phrase (replace this)
var smSearchPhrase;
// title (optional)
var smTitle = 'Realtime Buzz';
// items per page
var smItemsPerPage = 7;
// show or hide user profile images
var smShowUserImages = true;
// widget font size in pixels
var smFontSize = 11;
// height of the widget
var smWidgetHeight = 800;
// sources (optional, comment out for "all")
//var smSources = ['twitter', 'facebook', 'googleblog', 'identica'];
</script>
<script type="text/javascript" language="javascript" src="http://socialmention.s3.amazonaws.com/buzz_widget/buzz.js"></script>
I think your form is submitting back to the backend, you need to stop the form from doing that by returning false from onsubmit or canceling the event.
So this should work:
<form onsubmit="return smSearch();">
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button>Submit</button>
<input type="reset">
</form>
And return false in your JavaScript:
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
return false;
}
Personally I'd use preventDefault() on the event argument (not shown here), but that only works across all browsers when you also include a JavaScript library like jQuery as some versions of IE use a bubble property on the event or something.

Categories

Resources