Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery set different input text and value

right now I'm using $.val() to set an input's value. But I want the user to see a different text in the input, and still send the value set with val() to the server. I tried using $.text() but it doesn't work. Is there a way to set the html value attribute and also set a distinct text inside the input for th## Heading ##e user to see?

I'm not posting any code because its pretty generic. The reason I need this is because I want to display a nice date string in the text (I'm using a datetime picker) and send a compacted version of the string to the server.

EDIT

Ok, hope this helps:

<input class="form-control date" id="booking_time" name="hour" type="text">

In Javascript I have something like:

var date_booked = new Date()
$("#booking_time").val(date_booked.toDateString());

But I want the input's value that is sent to the server to be the date whithout the toDateString proccessing, and still show the date.toDateString() in the text box. To do that, I hoped this would work:

$("#booking_time").val(date_booked);
$("#booking_time").text(date_booked.toDateString());

But it doesn't.

like image 795
Alejandro Veintimilla Avatar asked Oct 30 '22 10:10

Alejandro Veintimilla


1 Answers

You can try storing the date you want to send to the server in a variable and then hook into the click event of the form's submit button to change the value right before submitting like so:

var date_booked = new Date()
$("#booking_time").val(date_booked.toDateString());

$("#id-of-submit-button").on("click", function() {
    $("#booking_time").val(date_booked);
});

The only problem is that if the user edits the input then it will overwrite their edit and send the variable instead. To get around this you can use another variable to detect a change in the input:

var submitvardate = true;
var date_booked = new Date()
$("#booking_time").val(date_booked.toDateString());

$("#id-of-submit-button").on("click", function() {
    if (submitvardate) {
        $("#booking_time").val(date_booked);
    }
});    

$("#booking_time").on("change", function() {
    submitvardate = false;
});
like image 81
B. Aikey Avatar answered Nov 08 '22 04:11

B. Aikey