Get parent element node when child node is matched - javascript

This is my code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
$.get(
"code.xml",
function(data) { xml=data; },
"html"
);
function get_list(){
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find('[value="'+$('#select').val()+'"]');
$nodes = $title.find('*');
var result='';
$nodes.each(function(){
result += $(this).attr('value');
result += ' ';
});
$("#result").html(result);
}
</script>
</head>
<input type="text" id="select">
<input type="button" name="button" value="Search" onclick="get_list()" >
<div id="result">
</div>
</html>
This is my xml file:
<root>
<child_1 entity_id = "1" value="india">
<child_2 entity_id = "2" value="gujarat">
<child_3 entity_id = "3" value="Ahemdabad"/>
<child_4 entity_id = "4" value="Surat"/>
<child_5 entity_id = "5" value="Rajkot"/>
</child_2>
</child_1>
<child_6 entity_id = "6" value="Rasia">
<child_7 entity_id = "7" value="state">
<child_8 entity_id = "8" value="cty"/>
<child_9 entity_id = "9" value="cty1"/>
<child_10 entity_id = "10" value="cty2"/>
</child_2>
</child_6>
</root>
With this code I get the child node value.
I wanted something, like when i enter in textbox any of city name: Ahemdabad, Surat, Rajkot; then its match on my xml file returns me country name like India.
Thanks!

Try
var xml;
$.get(
"code.xml",
function(data) {
xml=data;
},
"html"
);
function get_list(){
var xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find('[value="'+$('#select').val()+'"]');
var ctrs = $xml.find('root').children();
$("#result").html($title.closest(ctrs).attr('value'));
}
Demo: Plunker

You can use this xpath
//*[#value='Ahemdabad']/parent::*/#value
Just replace 'Ahemdabad' with the desired city name

Related

Create a hidden field, add it to form elements being sent on form submit? [duplicate]

How do you create a hidden field in JavaScript into a particular form ?
<html>
<head>
<script type="text/javascript">
var a =10;
function test() {
if (a ==10) {
// ... Here i need to create some hidden field for form named = chells
}
}
</script>
</head>
<body >
<form id="chells" name="formsdsd">
<INPUT TYPE=BUTTON OnClick="test();">
</form>
</body>
</html>
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
You can use jquery for create element on the fly
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
or other way
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
I've found this to work:
var element1 = document.createElement("input");
element1.type = "hidden";
element1.value = "10";
element1.name = "a";
document.getElementById("chells").appendChild(element1);
insertAdjacentHTML does the trick, and is probably the easiest way, query for the parent, and then just ask to insert before the end, or after the beginning as you see fit, i.e:
document.querySelector('#chells').insertAdjacentHTML('beforeend',
"<input type='hidden' name='status' value='true' />")
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true.
You can also add multiple hidden fields.
Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();
CustomizePPT.setHiddenFields = function(){
var request = [];
var container = '';
console.log(arguments);
request = arguments[0].hidden;
console.log(arguments[0].hasOwnProperty('form'));
if(arguments[0].hasOwnProperty('form') == true)
{
if(arguments[0].form.status == 'true'){
var parent = document.getElementById("container");
container = document.createElement('form');
parent.appendChild(container);
Object.assign(container, {'id':arguments[0].form.formID});
}
}
else{
container = document.getElementById("container");
}
//var container = document.getElementById("container");
Object.keys(request).forEach(function(elem)
{
if($('#'+elem).length <= 0){
console.log("Hidden Field created");
var input = document.createElement('input');
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});
container.appendChild(input);
}else{
console.log("Hidden Field Exists and value is below" );
$('#'+elem).val(request[elem]);
}
});
};
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='container'>
</div>

Read XML node using ajax

I need to use ajax to read xml node values and use those values further in existing JavaScript function.
Sample XML -
<cars>
<car mfgdate="1 Jan 15" name="Ford" id="1">
<engine litres="3.0" cylinders="6"/>
</car>
<car mfgdate="1 Feb 15" name="Toyota" id="2">
<engine litres="2.2" cylinders="4"/>
</car>
</cars>
Here I need to display details of one car (Ex.Ford) at a time on screen.
There are separate fields on UI to display details like name, mfgdate, litres and cylinders.
If user press next button then next car(Ex. Toyota) details should appear on screen. I need to make ajax calls to do it.
Any help is much appreciated.
Thanks.
Ajax Call
$(document).ready(function(){
$.ajax({ type: "GET",
url: "Cars.xml",
dataType: "xml",
success: function (xml) {
var xmlDoc = $.parseXML(xml);
$xml = $(xmlDoc);
$xml.find('events event date').each(function () {
alert($(this).text() + "<br />");
});
}
});
});
You can find here an example but you have just to put the parse part inside your ajax response call (and also for use as you designed your style ) :
var xmlString = '<cars>'+
'<car mfgdate="1 Jan 15" name="Ford" id="1">'+
'<engine litres="3.0" cylinders="6"/>'+
'</car>'+
'<car mfgdate="1 Feb 15" name="Toyota" id="2">'+
'<engine litres="2.2" cylinders="4"/>'+
'</car>'+
'<car mfgdate="1 Jan 16" name="SONACOM" id="3">'+
'<engine litres="4.0" cylinders="8"/>'+
'</car>'+
'</cars>';
// used to inc or decrements throw cars
var i = 0;
$(document).ready(function(){
xml = $.parseXML( xmlString );
$xml = $( xml );
$cars = $xml.find( "car" );
getCar($cars)
$("#btnnext").click(function(){
i++;
getCar($cars);
})
$("#btnprev").click(function(){
i--;
getCar($cars);
})
function getCar(cars) {
var html ="";
if(cars.length != 'undefined') {
if(cars.length > 0) {
if(i<cars.length){
var name = $(cars[i]).attr('name');
var mfgdate = $(cars[i]).attr('mfgdate')
var $engine = $(cars[i]).find('engine');
var litres = $($engine).attr('litres');
var cylinders = $($engine).attr('cylinders');
html += "<div>Name : "+name+"</div>";
html += "<div>Mfgdate : "+mfgdate+"</div>";
html += "<div>Litres : "+litres+"</div>";
html += "<div>Cylinders : "+cylinders+"</div>";
$("#carinfo").html(html);
btnClick();
}
}
}
}
function btnClick() {
i == 0 ? $("#btnprev").attr("disabled","disabled") :$("#btnprev").removeAttr("disabled");
i == $cars.length-1 ? $("#btnnext").attr("disabled","disabled") : $("#btnnext").removeAttr("disabled");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnprev" disabled>prev</button>
<button id="btnnext" disabled>next</button>
<br> <br>
<div id ="carinfo">
</div>

Generating a table with jQuery with XML data

I am new to jQuery, and js for that matter. I am trying to create a table from XML data, but I can't get the output correct. Here is what I have so far:
HTML:
<table id="daily_fruit">
<tbody>
</tbody>
</table>
jQuery:
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('daily_fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
)
.append($('<td>')
.append($type))
});
});
Current Output:
MonTuesWedThur
appleorangebananapear
Desired Output:
Mon apple
Tues orange
Wed banana
Thur pear
I think I am close, but I just can't figure it out.
Try modifying your XML so that each fruit is within its own tag. Then instead of finding the "daily_fruit" tag for your each loop, use the "fruit" tag.
Here's a jsfiddle:
https://jsfiddle.net/57wgab88/
var xml = '<daily_fruit><fruit><day>Mon</day><type>apple</type></fruit><fruit><day>Tues</day><type>orange</type></fruit><fruit><day>Wed</day><type>banana</type></fruit><fruit><day>Thur</day><type>pear</type></fruit></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
.append($('<td>')
.append($type))
)
});
});
Given such XML structure, you're supposed to iterate through <day> elements instead. Assuming that each <day> is always followed by corresponding <type> element :
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('day').each(function() {
var $day = $(this).text();
var $type = $(this).next("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
.append($('<td>')
.append($type))
)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="daily_fruit">
<tbody>
</tbody>
</table>

Populating dropdown from JSON string that was returned from a PHP CODE

I am returning a JSON array from my PHP class. Part of the code is as follows:
...
echo json_encode($users);
return json_encode($users);
?>
The echo statement of the above code is as follows:
[
{
"ID": "1",
"firstname": "Jane",
"school": "Frohj"
},
{
"ID": "2",
"firstname": "Mathew",
"school": "Lebrasky"
},
{
"ID": "3",
"firstname": "BAHUUU",
"school": "uni of kansas"
}
]
Now, in my html form i have a DROPDOWN.
<fieldset>
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<select id = "myList">
<option value = "1">I WANT TO DISPLAY USER'S NAME HERE</option>
<option value = "2">I WANT TO DISPLAY USER'S NAME HERE</option>
</select>
</p>
</fieldset>
I want to display users firstnames as the fields in the dropdown box. The values for this, is obtained from the JSON that was passed. Now how do i, retrieve the JSON and populate the dropdown box with firstnames of users.
You can decode to json result by json_decode($users); this function to convert json result it to array.
with the help of loop you can easily print your options.
Think your select should be empty at the beginning, then new options should be appended with javascript.
<select id = "myList"></select>
<script type="text/javascript">
var data = SOME_SORTOF_GET_JSON(), // get json from your existing function
select = document.getElementById("myList"),
newOption;
for(var i = 0, item; item = data[i]; ++i) {
newOption = new Option(item.firstname, item.id);
select.add(newOption);
}
</script>
Good luck.
Something like this:
head of the html page (with php extension)
<?php include 'pathTo/find.php' ?>
in your script tag:
var
i, len,
html = ''
list = <?php echo getUsers(); ?>;
for ( i = 0; len = list.length; i < len ) {
html += '<option value="'+ i +'">'+ list[i].firstname +'</option>';
}
// $( html ).appendTo( $( '#myList' ) ); <-- jQuery method
document.getElementById( 'myList' ).innerHtml = html;
your body tag:
<fieldset>
<legend>Selecting elements</legend>
<p>
<label>Select list</label>
<select id = "myList">
</select>
</p>
</fieldset>

get parent element attribute value

this is my xml document:-
<root>
<child_1 entity_id = "1" value="india">
<child_2 entity_id = "2" value="gujarat">
<child_3 entity_id = "3" value="Ahemdabad"/>
<child_4 entity_id = "4" value="Surat"/>
<child_5 entity_id = "5" value="Rajkot"/>
</child_2>
</child_1>
</root>
this is my javascript html code:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
var ind_sex;
$.get(
"code.xml",
null,
function (data) {
xml = data;
},
"xml"
);
function get_list() {
var city = $('#name').val();
alert(city);
var xPath = '//*[#value = "city"]' +
'/../../#value';
var iterator = xml.evaluate(xPath, xml.documentElement, null,
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
var thisNode = iterator.iterateNext();
var str = '';
while (thisNode) {
if (str) {
str += ', ';
}
str += thisNode.textContent;
thisNode = iterator.iterateNext();
}
$("#result").text(str);
}
</script>
</head>
<body>
<input type="text" id="name"></input>
<input type="button" name="button" value="Search" onclick="get_list()">
<div id="result">
</div>
</body>
</html>
here i am try to input in textbox city name if its match on my xml file then its return me there country name.
i dont get any error but not getting result.
i think problem in my xPath pleasae help me out of this.
Use:
var xPath = '//*[#value = "' + city + '"]/../../#value';
An equivalent expression is:
var xPath = '//*[*/*[#value = "' + city + ']]/#value';
As far as I remember, lists don't work like that... they're variables associated with a given value, so it's more like:
list($a, $b, $c) = [1, 2, 3];
Anyway, why don't you take a look at the 'Lists' section in the phpredis page? It's one of the recommended PHP clients for Redis, and its examples are quite clear

Categories

Resources