I had one for-loop in that for loop one div data and summit button.
Code i tried :
for(i=0; i<response.data.length; i++){
var job = '<div class="job-headers">';
job += '<h3>'+response.data[i].job_title+'</h3>';
job += '<h5>'+response.data[i].location+'</h5>';
job += '<h5>'+response.data[i].description+'</h5>';
job += '<h5> Created on :'+response.data[i].created_at+'</h5>';
job += '<h5> Status :'+response.data[i].job_status+'</h5>';
**show****job += '<div><h2>Title: ' + response.data[i].job_title + <h2>;
job += '<h2>Title: ' + response.data[i].job_role + <h2>';
$job+= '</div>'
****** job += '<input type="submit" class="submit-button" value="submit">';
$(".submit-button").click(function() {
$(this).prev('div').toggle();
});
job += '</div>';
$('#job-preview').append(job);
}
});
});
first button only show the first div second button not working? any ides???
The issue is because you're creating multiple elements with the same id
attribute in your loop. This is invalid as they must be unique within the DOM. This is the reason it only works for the first button.
To fix this problem remove the id
attribute and use a common class on the button elements. Then you can create a single event handler bound to all those buttons. You can use DOM traversal to only toggle the div
relative to the clicked button, like this:
var response = { data: [{ job_title: 'Title 1', job_role: 'Role 1' }, { job_title: 'Title 2', job_role: 'Role 2' }] } for (i = 0; i < response.data.length; i++) { var job = '<div class="job-headers">'; job += '<h3>' + response.data[i].job_title + '</h3>'; // other fields... job += '<div><h2>Title: ' + response.data[i].job_title + '</h2>'; job += '<h2>Title: ' + response.data[i].job_role + '</h2></div>' job += '<input type="submit" class="submit-button" value="submit">'; job += '</div>'; $('#job-preview').append(job); } $(".submit-button").click(function() { $(this).prev('div').toggle(); })
.job-headers>div { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="job-preview"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.