2

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>
8
  • As another answer already states, you need to use event delegation since the element is created after the DOM loads - learn.jquery.com/events/event-delegation Commented Nov 12, 2020 at 16:03
  • Where is #get_medicos located at all in the HTML? Commented Nov 12, 2020 at 16:06
  • is the section on which the doc's info is generated after being fetched from the dB Commented Nov 12, 2020 at 16:07
  • @andremonteiro1996 did the delegate version of the click work then? Commented Nov 12, 2020 at 16:08
  • nope, still doesn't work, and it's really bugging me why Commented Nov 12, 2020 at 16:09

4 Answers 4

3

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); 

})

});
Sign up to request clarification or add additional context in comments.

6 Comments

this worked halfway was able to scroll to the form and get the name of the doctor filled, only this is, it doesn't fill the name with the correct one. always goes for the last value of the generated cards
The original post was about the click event. That is working now. you have to work on the logic to get the required details. However if you can share the logic you are using to find the doctor's information then I can help you further.
the supposed logic is that the index generates a section with 3 random doctors, that in which you can perform a search and the make an appointment with the preferred doctor by clicking the button. that will take you to a form that will fill the name and specialty of the doctor on which card the button was pressed.
And, What not working currently is? When you click the MakeAppointment button (which are generated according to question) are not propagating the correct doctor information? You need to share the extended logic code which you have written currently.
No worries, you don't need to work on index logic, you can pass the data through event. check this fiddle, I have passed the doctor information and name through data attribute and which can be used in the click event. observe the data- attribute in the <a> tag and same is used in the click event. jsfiddle.net/0q3kpyfv/2
|
3

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

11 Comments

done this, doesnt seeem to work, maybe it's because of the files?
Can you please elaborate on that?
you do 3 'append' with same id
Attaching the listener to #get_medicos should work, but it does look like you have multiple divs with the same id. Since only one ID of a given name should exist, your event will only be bound to the first one it finds. If you update #marcar to use a class, or a dataset you will probably have better luck
The for loop works fine since every doctor has it's own page working with the id
|
0

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

Comments

-1

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.

3 Comments

He is trying to add the element to dom, the example you have posted does't replicate that.
@SachinVishwakarma because I didn't have anything to append to, $('#get_medicos') does not exist to append on.
#get_medicos is the section on wich the div with the doc's info is generated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.