Updating input, to update variable, to update table

Viewed 55

I am trying to create a simple table where you enter a registration number, and then the car name is put in to the cell adjacent to it.

I am using variables and when writing the if statement, it goes either one of two ways despite the conditions.

Below is the code for the if statement:

$("input[type='text']").change(function(){
$(this).closest('td').text($(this).val())});

var car1 = "Little White";
var car_1_reg = "NP60UQQ";

var car_reg_1 = $("#car-1-reg").html();
var car_name_1 = $("#car-1-name").html();
$(".confirm").click(function() {
if (car_reg_1 != car_1_reg) {
    car_name_1.innerText = 'Not a valid Registration';
}   else {
    car_name_1.textContent = car1;
}});

and I have uploaded the full project to jsfiddle here: https://jsfiddle.net/Coxy/pyho3as2/1/

I have spent most of the day trying to get the first part to work, once I have that right I can apply the logic across to the other parts (enter miles left and update miles till charge etc.

Any pointers would be really appreciated.

1 Answers

First, you're reading the dynamic-input during doc.ready, so it will never have the updated value. This needs to move into the click handler:

var car_reg_1 = $("#car-1-reg").html();
$(".confirm").click(function() {
    if (car_reg_1 != car_1_reg) {

becomes

$(".confirm").click(function() {
    var car_reg_1 = $("#car-1-reg").html();
    if (car_reg_1 != car_1_reg) {

next is that #car-1-reg is an input, so need to use .val()

var car_reg_1 = $("#car-1-reg").val();

however, the input for car-1-reg is removed from the DOM with this line in the input change event

$(this).closest('td').text($(this).val());

so at the time of checking (inside the click event) that element no longer exists $("#car-1-reg").length === 0) with the value now stored in the parent td.

There are two ways to fix this

  1. Give the td an id that you can reference, eg

and access that (inside the confirm click handler)

var car_reg_1 = $("#car-1-reg-td").text();

updated fiddle using this approach: https://jsfiddle.net/6oLvp7f5/

or

  1. don't remove the input, but hide it
<td><span></span><input id="car-1-reg"...

and

$("input[type='text']").change(function() {
    $(this).closest('td').find("span").show().text($(this).val());
    $(this).hide();
});

then you can reference the input directly in the confirm click handler (using .val()).

This also has the advantage that if you ever want a "reset" you can hide the span and show the input.

Related