Button click function not working in jQuery

Viewed 82

So I'm developing a website for a medical clinic and they asked me to add a button beneath every doctor to make an appointment.

this is what i have for the doctors section

for (var i = 0; i < 3; i++) {
    $('#get_medicos').append(
        '<div class="col-md-3 dummy">' +
            '<div class="text-box">' +
                '<img src="assets/images/corpo-clinico/' + medico[i].ficheiro + '" alt="" class="img-responsive"/>' +
                '<div class="clearfix"></div>' + 
                '<div class="text-box white padding-3">' +
                    '<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
                    '<p>' + medico[i].especialidade + '</p>' +
                    '<a id="marcar" type="button" class="btn btn-primary">Marcar consulta</a>' +
                '</div>' +
            '</div>' +
        '</div>'
    );
}

The then code for the click function (that doesn't work):

$('#marcar').click(function() {
    var offset = $('#marcacao').offset();
    $('html, body').animate({
        scrollTop: offset.top-100,
        scrollLeft: offset.left
    }, 1000);
    $('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(medico[i].especialidade);
    $('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(medico[i].nome);
    console.log('test');
});

This is all inside a $(document).ready(function() {}); and what should do is when i click that button beneath the doctor, should go up to the form and fill the doctor's name and specialty... but it seems it's not working for some reason... this is a copy of other click functions in the code, but they seem to work fine.

HTML form:

<div id="marcacao-consulta" data-target="#marcacao-consulta">
    <div class="row">
        <div class="col-md-6 col-lg-6 col-sm-12">
            <div class="section">
                <label class="field select prepend-icon">
                    <select id="especialidade-marcacao" class="gui-input">
                        <option id="especialiade-default" value="default">Escolha a especialidade</option>
                        <?
                                                                        $query = $dbHandle->prepare("
                                                                            SELECT `especialidade` 
                                                                            FROM `especialidade`
                                                                            ORDER BY `especialidade` ASC
                                                                        ");
                                                                        $query->execute();
                                                                        if ($query->rowCount() > 0) {
                                                                            while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
                        <option value="<?=$row["especialidade"]; ?>"><?=$row["especialidade"]; ?></option>
                        <? }
                                                                        } else { ?>
                        <option value="">Nenhum resultado</option>
                        <? }
                                                                    ?>
                    </select>
                    <span class="field-icon"><i class="fas fa-heartbeat"></i></span>
                </label>
            </div>
        </div>
        <div class="col-md-6 col-lg-6 col-sm-12">
            <div class="section">
                <label class="field select prepend-icon">
                    <select id="corpo-clinico-marcacao" class="gui-input">
                        <option id="corpo-clinico-default" value="default">Escolha o médico</option>
                        <?
                                                                        $query = $dbHandle->prepare("
                                                                            SELECT `nome` 
                                                                            FROM `medico`
                                                                            ORDER BY `nome` ASC
                                                                        ");
                                                                        $query->execute();
                                                                        if ($query->rowCount() > 0) {
                                                                            while ($row = $query->fetch(PDO::FETCH_ASSOC)) { ?>
                        <option value="<?=$row["nome"]; ?>"><?=$row["nome"]; ?></option>
                        <? }
                                                                        } else { ?>
                        <option value="">Nenhum resultado</option>
                        <? }
                                                                    ?>
                    </select>
                    <span class="field-icon"><i class="fas fa-user-md"></i></span>
                </label>
            </div>
        </div>
        <div class="col-md-12 col-lg-12 col-sm-12">
            <div class="section">
                <label class="field prepend-icon">
                    <input id="nome" class="gui-input" type="text" placeholder="Nome Completo">
                    <span class="field-icon"><i class="fas fa-user"></i></span>
                </label>
            </div>
            <div class="section">
                <label class="field prepend-icon">
                    <input id="email" class="gui-input" type="text" placeholder="Endereço de correio eletrónico">
                    <span class="field-icon"><i class="fas fa-envelope"></i></span>
                </label>
            </div>
            <div class="section">
                <label class="field prepend-icon">
                    <input id="telefone" class="gui-input" type="text" placeholder="Telefone/Télemovel">
                    <span class="field-icon"><i class="fas fa-phone-square"></i></span>
                </label>
            </div>
            <div class="section">
                <label class="field prepend-icon">
                    <input id="tipo" class="gui-input" type="text" value="consulta" disabled>
                </label>
            </div>
        </div>
    </div>
</div>
4 Answers

if you create the button after your event, you could have problem so, use the delegate version of click:

$('div').on('click', 'a', (function()....

and better put an id on the ancestor div:

'<div class="text-box white padding-3" id="mydiv"'
          :
 $('#mydiv').on('click', 'a', (function()....

another thing, with the loop you will have same id more time in your html??its no good.

so you'll have to rebuild your program logic...and bind the event with the right button (use a common class) it will be better than an id

You have to add the element and register the event for the element. Here is the fiddle which works for you

https://jsfiddle.net/0q3kpyfv/

Your sample HTML

<div id="get_medicos">
</div>

Sample jquery code Notice I have added the data-val attribute to the added anchor tag which will help you to get the information and perform the logic based on which button is clicked. you can pass dynamic data to data-val attribute and use it in click event.

$(document).ready(function() {

var sampleString = "";
var medico = [{'especialidade':'speciality 0','nome':'Doctor 0'},{'especialidade':'speciality 1','nome':'Doctor 1'},{'especialidade':'speciality 2','nome':'Doctor 2'}]

for (var i = 0; i < 3; i++) {

var doctorData = medico[i];

    $('#get_medicos').append(
        '<div class="col-md-3 dummy">' +
            '<div class="text-box">' +
                '<img src="assets/images/corpo-clinico/' + medico[i].especialidade + '" alt="" class="img-responsive"/>' +
                '<div class="clearfix"></div>' + 
                '<div class="text-box white padding-3">' +
                    '<h5 class="less-mar1 text-blue">' + medico[i].nome +'</h5>' +
                    '<p>' + medico[i].especialidade + '</p>' +
                    '<a id="marcar" data-doctor-especialiadade="'+medico[i].especialidade+'" data-doctor-nome="'+medico[i].nome+'" type="button" class="btn btn-primary">Marcar consulta'+i+'</a>' +
                '</div>' +
            '</div>' +
        '</div>'
    );
};



$('#get_medicos').on('click','a',function(event){

var elementClicked = event.target;
var doctorEspecialiadade = $(elementClicked).data('doctor-especialiadade');
var doctorName = $(elementClicked).data('doctor-nome');


 $('#marcacao-consulta').find('#especialidade-marcacao option[id="default"]').text(doctorEspecialiadade);
    $('#marcacao-consulta').find('#corpo-clinico option[id="default"]').text(doctorName); 

})

});

If you bind the event to the parent element, and filter by the children, you can listen to any new elements that are added, doesn't matter how many.

<div class="container"></div>

<button class="js-add-new">Add new</button>
const $addNew = $('.js-add-new')
const $container = $('.container')
let count = 0

$addNew.on("click", () => {
  count += 1
  $container.append(`
    <div>
      <button>log me ${count}</button>
    </div>
  `)
})

$container.on("click", "button", (event) => {
  console.log(event.currentTarget)
})

A working example: https://codepen.io/alexmccabe/pen/jOrXZxj?editors=1111

The button click is working. Here is a fiddle showing it does:

https://jsfiddle.net/bradberkobien/qL4m10y6/3/

There must be an issue with the code that comes before the console.log("test") line within the click. I would use the debugger to help you with that.

Related