Vojtas
Vojtas

Reputation: 3

How to access the ID of an HTML element

How to get the value from "id" instead of from "value" and show it on the page? Now I have Holzart:3, I want to have Holzart:Lärche.

I have this function:

$(document).ready(function() {
  $("input[name='holzart']").click(function() {        
    PobierzWartosc2();
  });
});

function PobierzWartosc2() {
  $('#aus2').html('');
  $("input[name='holzart']").each(function() {
  if (this.checked == true) {
    $('#aus2').append('Holzart:'+ $(this).val()) }
  });
}

and this HTML:

<tr><td><label>
<input type="radio" name="holzart" value="3" id="Lärche" >Lärche</label></td></tr>

Upvotes: 1

Views: 462

Answers (6)

Andrzej Ośmiałowski
Andrzej Ośmiałowski

Reputation: 1504

So change your code. You're appending value, not ID.

$('#aus2').append('Holzart:'+ $(this).val()) }
    });

should be

$('#aus2').append('Holzart:'+ $(this).attr('id')) }
    });

Edit
As others recommended, it's better to use this.id instead of $(this).attr('id').

Upvotes: 0

Tomalak
Tomalak

Reputation: 338208

Here is an improved version of your code, with annotations

// $(document).ready() is superfluous, use $()
$(function() {
  $("input[name='holzart']").click(function() {
    // call the function in the correct context to retain the meaning of "this"
    PobierzWartosc2.call(this);
  });
});

function PobierzWartosc2() {
  // just overwrite the current content instead of calling .html('') first
  $('#aus2').text( this.checked ? this.id : '' );
}

basically, you want:

$(function() {
  $(":radio[name='holzart']").click(function() {
    $('#aus2').text( this.checked ? this.id : '' );
  });
});

Other than that, I agree with ThiefMaster that id is terrible place to store any kind of data.

Use HTML5 data-* attributes or store additional data - or a hidden <span> for example (if your page is not HTML5). In your case you cold even simply use the text of the associated <label>:

$(function() {
  $(":radio[name='holzart']").click(function() {
    var $label = $("label[for='" + this.id + "']");
    $('#aus2').text( this.checked ? $label.text() : '' );
  });
});

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35822

Use this.id or $(this).attr('id'). The difference is that, this is a JavaScript object, referencing to the radio button which is clicked, but $(this) is a jQuery object, wrapping JavaScript object to provide more functionality.

Upvotes: 0

Ankur
Ankur

Reputation: 33637

instead of $(this).val() you need to use $(this).attr("id")

Upvotes: 0

Mark Perry
Mark Perry

Reputation: 1735

$('#aus2').append('Holzart:'+ $(this).attr('id'))

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318508

Simply use this.id instead of $(this).val().

However, the ID is one of the worst attributes to store data unless it's the actual ID of the object. You might want to consider adding data-something="whatever" and then access it using $(this).data('something')

Upvotes: 3

Related Questions